AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

Functions

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.

Key ideas

Remember

Kinds of functionbuilt-in: len(), int(), max(); from a module: math.sqrt(); user-defined: written with def
Defaultsdef area(l, b=2):
    return l * b
print(area(5), area(5, 3)) # 10 15
Keyword argumentsf(1, c=3, b=2) is fine; f(a=1, 2) is a SyntaxError
Two values backdef mm(a, b): return a + b, a * b, so mm(2, 3) gives (5, 6)
No returnr = f() for a function that only prints: r is None
Local and globalx = 9 inside a function makes a new local x; after global x the function changes the outer x

Watch out

Worked example

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