Functions
def, return, *args, **kwargs, scope, and lambda
Skills taught: python.functions, python.def, python.return, python.args, python.lambda
Defining and calling functions
# Define a function
def greet(name):
print(f'Hello, {name}!')
# Call it
greet('Prashant') # Hello, Prashant!
greet('World') # Hello, World!
# Function with return value
def add(a, b):
return a + b
result = add(3, 4)
print(result) # 7
# Multiple return values (actually returns a tuple)
def min_max(numbers):
return min(numbers), max(numbers)
lo, hi = min_max([3, 1, 9, 2, 7])
print(lo, hi) # 1 9
Default parameters and keyword arguments
# Default parameter values
def greet(name, greeting='Hello'):
return f'{greeting}, {name}!'
print(greet('Prashant')) # Hello, Prashant!
print(greet('Prashant', 'Hi')) # Hi, Prashant!
print(greet(greeting='Hey', name='Bob')) # keyword args
# *args — variable positional arguments (becomes a tuple)
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100
# **kwargs — variable keyword arguments (becomes a dict)
def display(**info):
for key, val in info.items():
print(f'{key}: {val}')
display(name='Prashant', city='Delhi', age=28)
# name: Prashant | city: Delhi | age: 28
Lambda and type hints
# lambda — anonymous single-expression function
square = lambda x: x ** 2
print(square(5)) # 25
# Useful with sorted()
people = [('Bob', 30), ('Alice', 25), ('Charlie', 35)]
sorted_by_age = sorted(people, key=lambda p: p[1])
print(sorted_by_age)
# [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
# Type hints — document expected types
def greet(name: str, times: int = 1) -> str:
return (f'Hello, {name}! ' * times).strip()
print(greet('Prashant', 3))
# Hello, Prashant! Hello, Prashant! Hello, Prashant!
# Avoid mutable default argument gotcha!
# ❌ Wrong — list is shared across all calls
def bad(items=[]):
items.append(1)
return items
# ✅ Correct — create fresh list each call
def good(items=None):
if items is None:
items = []
items.append(1)
return items
Frequently Asked Questions
What happens if a function has no return statement?
It implicitly returns None. All Python functions return something — if you don't specify, it's None. This is why print() returns None if you try to use its result.
What is a docstring and why does it matter?
A docstring is the triple-quoted string right after def — it documents what the function does, its parameters, and its return value. Python exposes it via help(function) and __doc__. IDEs show it on hover. It's the standard way to document Python code — more important than comments.