Python Functions Cheat Sheet
Parameters, defaults, *args, **kwargs, lambdas, and scope rules.
Updated
# → value shows what an expression returns. # name → value shows what a variable holds after that line.
Defining and calling#
def greet(name, greeting="Hello"):
"""Return a greeting.""" # docstring
return f"{greeting}, {name}!"
greet("Asha") # → 'Hello, Asha!'
greet("Ravi", "Welcome") # → 'Welcome, Ravi!'
greet(greeting="Hi", name="Meera") # → 'Hi, Meera!'A function without return returns None. return ends the function immediately.
Kinds of parameters#
def f(a, b=2, *args, key, flag=False, **kwargs):
return a, b, args, key, flag, kwargs
f(1, key="k") # → (1, 2, (), 'k', False, {})
f(1, 5, 6, 7, key="k", x=9) # → (1, 5, (6, 7), 'k', False, {'x': 9})Order: required → defaults → *args → keyword-only → **kwargs.
Mutable default trap#
def add(item, items=None): # never items=[]
if items is None:
items = []
items.append(item)
return items
add(1) # → [1]
add(2) # → [2]Defaults are created once, when the function is defined, so a [] default would be shared by every call.
Returning several values#
def min_max(nums):
return min(nums), max(nums) # returns a tuple
low, high = min_max([4, 9, 1]) # low → 1Unpacking arguments#
def add3(a, b, c):
return a + b + c
add3(*[1, 2, 3]) # → 6
add3(**{"a": 1, "b": 2, "c": 3}) # → 6Lambda functions#
square = lambda n: n * n
square(4) # → 16
people = [("Asha", 21), ("Ravi", 25), ("Meera", 19)]
sorted(people, key=lambda p: p[1]) # → [('Meera', 19), ('Asha', 21), ('Ravi', 25)]
max(people, key=lambda p: p[1]) # → ('Ravi', 25)
sorted(["b", "A", "c"], key=str.lower) # → ['A', 'b', 'c']One expression only, no statements. Use def for anything longer or reused.
Scope (LEGB)#
Python looks up names in this order: Local → Enclosing → Global → Built-in.
count = 0
def bump():
global count # needed to *assign* a global
count += 1
bump() # count → 1
def counter():
n = 0
def inc():
nonlocal n # assign to the enclosing function's n
n += 1
return n
return inc
tick = counter()
tick(), tick() # → (1, 2)Assigning to a name anywhere inside a function makes it local there. Prefer returning values over global.
Recursion#
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
factorial(5) # → 120Default recursion limit: about 1,000 calls (sys.getrecursionlimit()).
Decorators#
from functools import wraps
def shout(func):
@wraps(func) # keep the original name and docstring
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout # same as: hello = shout(hello)
def hello(name):
return f"hi {name}"
hello("asha") # → 'HI ASHA'
hello.__name__ # → 'hello'from functools import lru_cache
@lru_cache(maxsize=None) # remember previous results
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(50) # → 12586269025Generators#
def countdown(n):
while n > 0:
yield n # pause and hand back a value
n -= 1
list(countdown(3)) # → [3, 2, 1]
sum(n * n for n in range(4)) # → 14Values are produced lazily, one at a time, and a generator can be consumed only once.
Type hints#
def area(width: float, height: float = 1.0) -> float:
return width * height
area(3, 2.5) # → 7.5Hints document intent for editors and tools like mypy; Python does not enforce them at runtime.
Built-in functions worth knowing#
Full lessons: Functions, Parameters, Scope, Lambda, Recursion, Decorators, Generators.
Want the full explanations? Go to the Learn Python course →