def print_text():
print 'this is text'
print_text()
def print_this(x):
print x
print_this(3) # prints 3
n = print_this(3) # prints 3, but doesn't assign 3 to n
# because the function has no return statement
def square_this(x):
return x**2
def square_this(x):
"""Return the square of a number."""
return x**2
square_this(3) # prints 9
var = square_this(3) # assigns 9 to var, but does not print 9
one 'keyword argument' (has a default value)
def calc(a, b, op='add'):
if op == 'add':
return a + b
elif op == 'sub':
return a - b
else:
print 'valid operations are add and sub'
calc(10, 4, op='add') # returns 14
calc(10, 4, 'add') # also returns 14: unnamed arguments are inferred by position
calc(10, 4) # also returns 14: default for 'op' is 'add'
calc(10, 4, 'sub') # returns 6
calc(10, 4, 'div') # prints 'valid operations are add and sub'
def stub():
pass
def min_max(nums):
return min(nums), max(nums)
nums = [1, 2, 3]
min_max_num = min_max(nums) # min_max_num = (1, 3)
min_num, max_num = min_max(nums) # min_num = 1, max_num = 3
primarily used to temporarily define a function for use by another function
def squared(x):
return x**2
squared = lambda x: x**2
simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
return word[-1]
sorted(simpsons, key=last_letter)
sorted(simpsons, key=lambda word: word[-1])