- LPU MCA Semester 1
- CAB106
- Unit 1
CAB106 · Unit 1: Python and OOP introduction
Functions in Python
12 practice questions
Key points
- return gives back a value; no return means None
- args is a tuple and *kwargs is a dict
- Assignment inside a function creates a local name
- Mutable defaults are created once and shared
A function is defined with def name(parameters): and returns a value with return; without a return statement it returns None. Arguments can be positional or keyword (f(b=1, a=5)), and a positional argument may not follow a keyword argument. Parameters can have defaults (b=2). *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict; f(*t) unpacks a tuple into separate arguments.
Returning several values, as in return a, b, actually returns one tuple. Variables created by assignment inside a function are local, so they do not change a global of the same name unless declared with global. Functions can call themselves; recursion needs a base case, for example fact(n) = 1 if n <= 1 else n * fact(n - 1).
A documentation string placed first in the body becomes the function's __doc__.
Exam trap: default values are evaluated once, when def runs. A mutable default such as bag=[] is shared by every call that omits it, so values accumulate. Use None and create the list inside.
Try two questions
Which keyword is used to define a function in Python?
- func
- function
- define
- def
Show the answer
D. A function starts with def, then the name, parentheses and a colon.
Why not A: func is not a Python keyword.
Why not B: function is used in JavaScript, not Python.
Why not C: define is not a Python keyword.