# 01 Documentation a PSA
import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
# 02 What Good are Functions
def tax(bill):
"""Adds 8% tax to a restaurant bill."""
bill *= 1.08
print ("With tax: %f" % bill)
return bill
def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print ("With tip: %f" % bill)
return bill
meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)
With tax: 108.000000 With tip: 124.200000
# 03 Ample Examples
length = len(str(45))
print (length)
2
# 04 Function Junction
# Define your spam function starting on line 5. You
# can leave the code on line 11 alone for now--we'll
# explain it soon!
def spam():
"""print (eggs)"""
print ("Eggs!")
# Define the spam function above this line.
spam()
Eggs!
# 05 Call and Response
def square(n):
"""Returns the square of a number."""
squared = n**2
print ("%d squared is %d." % (n, squared))
return (squared)
# Call the square function on line 9! Make sure to
# include the number 10 between the parentheses.
square(10)
10 squared is 100.
100
# 06 No One Ever Does
def power(base, exponent): # Add your parameters here!
result = base**exponent
print ("%d to the power of %d is %d." % (base, exponent, result))
power(37, 4) # Add your arguments here!
37 to the power of 4 is 1874161.
# 07 Splat
def favorite_actors(*names):
"""Prints out your favorite actorS (plural!)"""
print ("Your favorite actors are:" , names)
favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")
Your favorite actors are: ('Michael Palin', 'John Cleese', 'Graham Chapman')
# 08 Functions Calling Functions
def one_good_turn(n):
return (n + 1)
def deserves_another(n):
return (one_good_turn(n) + 2)
deserves_another(10)
13
# 09 Practice Makes Perfect
def cube(number):
return (number ** 3)
def by_three(number):
if number % 3 == 0:
return (cube(number))
else:
return (False)
print (by_three(12))
print (by_three(10))
1728 False
# 10 I Know Kung Fu
# Ask Python to print (sqrt(25) on line 3.
print (sqrt(25)) # causes an error, just go ahead
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-10-d5ba772b9675> in <module>() 3 # Ask Python to print (sqrt(25) on line 3. 4 ----> 5 print (sqrt(25)) # causes an error, just go ahead NameError: name 'sqrt' is not defined
# 11 Generic Imports
# Ask Python to print (sqrt(25) on line 3.
import math
print (math.sqrt(25))
5.0
# 12 Function Imports
# Import *just* the sqrt function from math on line 3!
from math import sqrt
print (sqrt(25))
5.0
# 13 Universal Imports
# Import *everything* from the math module on line 3!
from math import *
# 14 Here Be Dragons
import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print (everything) # Prints 'em all!
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
# 15 On Beyond Strings
def biggest_number(*args):
print (max(args))
return (max(args))
def smallest_number(*args):
print (min(args))
return (min(args))
def distance_from_zero(arg):
print (abs(arg))
return (abs(arg))
biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)
10 -10 10
10
# 16 max
# Set maximum to the max value of any set of numbers on line 3!
maximum = max(1, 2.3, 5)
print (maximum)
5
# 17 min
# Set minimum to the min value of any set of numbers on line 3!
minimum = min(182, 1.0, 20)
print (minimum)
1.0
# 18 abs
absolute = abs(-42)
print (absolute)
42
# 19 type
# print (out the types of an integer, a float,
# and a string on separate lines below.
print (type(1))
print (type(1.0))
print (type(str(1)))
print (type(print))
<class 'int'> <class 'float'> <class 'str'> <class 'builtin_function_or_method'>
# 20 Review Functions
def shut_down(s):
if s == "Yes" or s == "yes" or s == "YES":
return ("Shutting down...")
elif s == "No" or s == "no" or s == "NO":
return ("Shutdown aborted!")
else:
return ("Sorry, I didn't understand you.")
# 21 Review Modules
import math
#from math import sqrt
print (math.sqrt(13689))
117.0
# 22 Review Built-In Functions
def distance_from_zero(para):
tp = type(para);
if tp == int or tp == float:
return (abs(para))
else:
return ("Not an integer or float!")
print (distance_from_zero(1.5))
print (distance_from_zero("1.5"))
1.5 Not an integer or float!