Definition
📌 Functions
Python functions are defined with the def keyword.
Syntax
syntax
def functionName(param1, param2=defaultValue):
# code
return valueExample
py
def add(a, b):
return a + b
result = add(4, 7)
print("Sum:", result)Output
outputSum: 11
Important Points
- Functions are defined with
def name(parameters):and a colon. - Parameters can have default values:
def greet(name="friend"):. - Python functions can return multiple values at once as a tuple:
return a, b. - A function without an explicit
returnimplicitly returnsNone.
Common Mistakes
- Forgetting the colon
:after the function signature. - Assuming a function without
returngives back the last computed value — it actually returnsNone. - Using a mutable default argument (like a list) — it's a well-known Python pitfall since defaults are evaluated once.
Interview Tip
🎯 Before your interview
A well-known intermediate Python gotcha: mutable default arguments (e.g.
def f(x=[]):) are shared across calls — be ready to explain why and how to avoid it (use None as the default instead).
