Python Functions
Python · Beginner
Definition
A function is a reusable block of code defined with def that takes parameters and returns a value.
Functions keep code organised, reusable and testable.
Diagram
Flowchart
Example: Default and keyword arguments
def greet(name, msg='Hello'):
return f'{msg}, {name}!'
print(greet('Ravi', msg='Hi'))Output: Hi, Ravi!
Key points
- *args and **kwargs accept variable arguments
- lambda creates small anonymous functions
- Avoid mutable default arguments
Interview questions
Why avoid def f(x=[])?
The same list is shared across calls.
What is a lambda?
A one-expression anonymous function, e.g. lambda x: x * 2.