Worksheets › Class 12 › Functions › Cheat sheet
Class 12 Functions: cheat sheet
CBSE Computer Science. 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
- def only defines a function; its body runs each time the function is called, and the call then returns to the line after it.
- Arguments are matched by position, keyword arguments by name; a positional argument cannot follow a keyword argument, and each parameter gets exactly one value.
- A default value is used only when that argument is not passed; parameters with defaults come after those without.
- return sends a value back and ends the function; with no return a function gives None; return a, b gives a tuple.
- A name given a value inside a function is local and hides a global of the same name; global x lets the function change the x outside.
- A list passed to a function is the same object, so changes made to it stay; giving a parameter a new value (n = n + 5) does not change the caller’s variable.
Remember
| 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 |
Watch out
- Thinking a function runs where it is defined: it runs only when it is called.
- Putting a keyword argument before a positional one, or giving one parameter two values.
- Using a function that only prints as if it gave a value: it gives None.
- Expecting a change to a number parameter to change the caller’s variable.
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
Practise Functions
Revise with this page, then practise: every Functions sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.