Functions are defined with def and called by name. Python supports default arguments, keyword arguments, and *args/**kwargs—flexible like JavaScript but with explicit parameter rules.
Defining and calling
def greet(name, prefix="Hi"):
return f"{prefix}, {name}!"
print(greet("Ada"))
print(greet("Grace", prefix="Hello"))
Return and scope
Functions return None implicitly if no return statement. Local variables do not leak unless declared global or nonlocal—prefer passing values and returning results.
Important interview questions and answers
- Q: Mutable default argument pitfall?
A: Defaults likedef f(x=[])share one list—useNoneand create inside the function. - Q: *args vs **kwargs?
A:*argscollects extra positional args as a tuple;**kwargscollects extra keyword args as a dict.
Self-check
- What keyword defines a function?
- What is returned if a function has no return statement?
Pitfall: Never use mutable defaults like def f(x=[])—use None and create inside the function.
Interview prep
- Mutable default pitfall?
def f(x=[])shares one list—useNonedefault and assignx = []inside.- *args and **kwargs?
*argstuple of extra positional args;**kwargsdict of extra keyword args.