Skip to main content
Foundation

Functions in Python

A function is a reusable block of code defined with def.

functions.py
def greet(name, greeting="Hello"):
"""Return a greeting message."""
return f"{greeting}, {name}!"

print(greet("PrepVerse")) # Hello, PrepVerse!
print(greet("PrepVerse", "Welcome")) # Welcome, PrepVerse!

Arguments​

arguments.py
def total(*numbers, **options):
s = sum(numbers)
return s * options.get("factor", 1)

print(total(1, 2, 3, factor=2)) # 12
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dict.

Lambda functions​

lambda.py
square = lambda x: x * x
print(sorted([3, 1, 2], key=lambda v: -v)) # [3, 2, 1]

Scope​

Variables assigned inside a function are local. Use global or nonlocal only when you really need to rebind an outer name.

CAUTION

Avoid mutable default arguments such as def f(items=[]). The same list is reused across calls. Use None and create the list inside the function.