# this one is like your scripts with argvdefprint_two(*args):print(args)*arg1, arg2 = argsprint(f"arg1: {arg1}, arg2: {arg2} ")# ok, that *args is actually pointless, we can just do thisdefprint_two_again(arg1,arg2="333"):print(f"arg1: {arg1}, arg2: %{arg2}")# this just takes one argumentdefprint_one(arg1):print(f"arg1: {arg1}")# this one takes no argumentsdefprint_none():print("I got nothing.")print_two("Zed","Shaw")print_two_again("Zed","Shaw")print_one("First!")print_none()
def add(a, b):
print("ADDING %d + %d" % (a, b))
return a + b
def complex_print(a, b):
return a + b, a - b, a * b, a / b
def subtract(a, b):
print("SUBTRACTING %d - %d" % (a, b))
return a - b
def multiply(a, b):
print("MULTIPLYING %d * %d" % (a, b))
return a * b
def divide(a, b):
print("DIVIDING %d / %d" % (a, b))
return a / b
print("Let's do some math with just functions!")
age = add(30, 5)
c1,c2,c3,c4 = complex_print(30, 5)
print(f"{c1},{c2},{c3},{c4}")
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
bmi = divide(weight, multiply(height, height))
print("That becomes: ", what, "Can you do it by hand?")
def f(x, y, z):
return x + y + z
print(f(1, 3, 2)) # returns 6
def g():
return 42
print(g()) # returns 42
# Note - the number of arguments provided must match the number of parameters!
print(g(2)) # will crash
print(f(1, 2)) # would also crash if it ran
# Some functions are already provided by Python
print("Type conversion functions:")
print(bool(0)) # convert to boolean (True or False)
print(float(42)) # convert to a floating point number
print(int(2.8)) # convert to an integer (int)
print("And some basic math functions:")
print(abs(-5)) # absolute value
print(max(2,3)) # return the max value
print(min(2,3)) # return the min value
print(pow(2,3)) # raise to the given power (pow(x,y) == x**y)
print(round(2.354, 1)) # round with the given number of digits
import math
print(math.factorial(20)) # much better...
# Note that the module name is included before the function name, separated by a .
def f(x):
print("x:", x)
y = 5
print("y:", y)
return x + y
print(f(4))
print(x) # will crash!
print(y) # would also crash if we reached it!
def f(x):
print("In f, x =", x)
x += 5
return x
def g(x):
y = f(x*2)
print("In g, x =", x)
z = f(x*3)
print("In g, x =", x)
return y + z
print(g(2))
# Another example
def f(x):
print("In f, x =", x)
x += 7
return round(x / 3)
def g(x):
x *= 10
return 2 * f(x)
def h(x):
x += 3
return f(x+4) + g(x)
print(h(f(1)))
# In general, you should avoid using global variables.
# You will even lose style points if you use them!
# Still, you need to understand how they work, since others
# will use them, and there may also be some very few occasions
# where you should use them, too!
g = 100
def f(x):
return x + g
print(f(5)) # 105
print(f(6)) # 106
print(g) # 100
# Another example
def f(x):
# If we modify a global variable, we must declare it as global.
# Otherwise, Python will assume it is a local variable.
global g
g += 1
return x + g
print(f(5)) # 106
print(f(6)) # 108
print(g) # 102
# We commonly write functions to solve problems.
# We can also write functions to store an action that is used multiple times!
# These are called helper functions.
def onesDigit(n):
return n%10
def largerOnesDigit(x, y):
return max(onesDigit(x), onesDigit(y))
print(largerOnesDigit(134, 672)) # 4
print(largerOnesDigit(132, 674)) # Still 4
# There are a few functions from modules you'll definitely want to use in the assignments
# First: the built-in round function has confusing behavior when rounding 0.5.
# Use our function roundHalfUp to fix this.
def roundHalfUp(d):
# Round to nearest with ties going away from zero.
# You do not need to understand how this function works.
import decimal
rounding = decimal.ROUND_HALF_UP
return int(decimal.Decimal(d).to_integral_value(rounding=rounding))
print(round(0.5)) # This evaluates to 0 - what!
print(round(1.5)) # And this will be 2 - so confusing!
print(roundHalfUp(0.5)) # Now this will always round 0.5 up (to 1)
print(roundHalfUp(1.5)) # This still rounds up too!
# Second: when comparing floats, == doesn't work quite right.
# Use almostEqual to compare floats instead
print(0.1 + 0.1 == 0.2) # True, but...
d1 = 0.1 + 0.1 + 0.1
d2 = 0.3
print(d1 == d2) # False!
print(d1) # prints 0.30000000000000004 (uh oh)
print(d1 - d2) # prints 5.55111512313e-17 (tiny, but non-zero!)
# Moral: never use == with floats!
# Python includes a builtin function math.isclose(), but that function
# has some confusing behavior when comparing values close to 0.
# Instead, let's just make our own version of isclose:
def almostEqual(x, y):
return abs(x - y) < 10**-9
# This will now work properly!
print(almostEqual(0, 0.0000000000001))
print(almostEqual(d1, d2))
def onesDigit(n):
return n%10
def testOnesDigit():
print("Testing onesDigit()...", end="")
assert(onesDigit(5) == 5)
assert(onesDigit(123) == 3)
assert(onesDigit(100) == 0)
assert(onesDigit(999) == 9)
assert(onesDigit(-123) == 3) # Added this test
print("Passed!")
testOnesDigit() # Crashed! So the test function worked!
import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
import math语句表示导入math包,并允许后续代码引用math包里的sin、cos等函数。