Built-in, module and user-defined functions: parameters and arguments, default and keyword arguments, return values, the flow of execution, and local and global scope.
| Kinds of function | built-in: len(), int(), max(); from a module: math.sqrt(); user-defined: written with def |
| Defaults | def area(l, b=2): return l * b print(area(5), area(5, 3)) # 10 15 |
| Keyword arguments | f(1, c=3, b=2) is fine; f(a=1, 2) is a SyntaxError |
| Two values back | def mm(a, b): return a + b, a * b, so mm(2, 3) gives (5, 6) |
| No return | r = f() for a function that only prints: r is None |
| Local and global | x = 9 inside a function makes a new local x; after global x the function changes the outer x |
What does this print?
def update(L, n):
for i in range(len(L)):
if L[i] % 2 == 0:
L[i] = L[i] + 5
n = n + 5
nums = [27, 18, 17, 13]
m = 10
update(nums, m)
print(nums, m)
Working: the list is the same object inside the function, so changes to it stay; n is a new local name
Answer: [27, 23, 17, 13] 10