- Vocabulary
x = 5
def f(y, z):
result = x + y + z
return result
print(f(1, 2)) # 8
print(f(3, 4)) # 12
# Vocabulary:
# global variable
# local variable
# statement
# expression
# function definition (or declaration)
# function call
# parameter
# argument
# return value
# return type
- Return Statements
def cube(x):
return x**3
print(cube(5)) # 125
Return ends the function immediately:
def cube(x):
print('A') # runs
return x**3
print('B') # does not run ('dead code')
print(cube(5)) # A, then 125
No return statement --> return None:
def f(x):
x + 42
print(f(5)) # None
- Print versus Return
# This is a common early mistake (confusing print and return):
def cubed(x):
print(x**3) # Here is the error!
print(3 + cubed(2)) # Error!
Once again (correctly):
def cubed(x):
return (x**3) # That's better!
print(3 + cubed(2))
- Different Parameter and Return Types
def sumOfSquares(a, b):
return ((a**2) + (b**2))
print(sumOfSquares(2, 3)) # 13 (4 + 9)
def isPositive(a):
return (a > 0)
print(isPositive(1.23)) # True
def cubedRoot(n):
return n**(1/3)
print(cubedRoot(3)) # 1.4422495703074083
- Function Composition
def f(x):
return x+1
def g(y):
return 10*f(y+1)
print(g(2))
- Helper Functions
def onesDigit(n):
return n%10
def largerOnesDigit(x, y):
return max(onesDigit(x), onesDigit(y))
print(largerOnesDigit(34, 72)) # 4
- Test Functions
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!
- Local Variable Scope
def f(x):
print('In f, x =', x)
return x+5
def g(x):
print('In g, x =', x)
return f(x+1)
print(g(2))
- Global Variable Scope
g = 100
def f(x):
return x + g
print(f(5)) # 105
print(f(6)) # 106
print(g) # 100
Another example:
g = 100
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