Cheat SheetsPython A–ZFunctions

Functions — Cheat Sheet

Python A–Z · 4 topics. Download the PDF or the Instagram carousel and share it.

Cheat Sheet · AiCanCode.org
Functions
Python A–Z4 topicsQuick revision reference
1

Functions — def, Return Values & Default Arguments

Functions are first-class objects defined with def, returning None unless told otherwise — with keyword arguments and default values that make call sites self-documenting.

  • No explicit return → the function returns None
  • Keyword arguments make call sites readable; defaults make params optional
  • NEVER use mutable defaults (list/dict) — use None + create inside
  • Returning a, b returns a tuple; unpack with x, y = f()
Defaults, keyword calls, tuple returns
def apply_discount(price, percent=10):     # percent is optional
    discounted = price * (1 - percent / 100)
    return round(discounted, 2)

apply_discount(1000)               # 900.0  — default used
apply_discount(1000, 25)           # 750.0  — positional
apply_discount(price=1000, percent=25)   # named — self-documenting

# "Multiple" return values = one tuple
def min_max(nums):
    return min(nums), max(nums)    # returns a tuple

lo, hi = min_max([4, 9, 1])        # unpacked
print(lo, hi)                      # 1 9

# Functions are objects
operations = {"double": lambda x: x * 2, "square": lambda x: x ** 2}
print(operations["square"](6))     # 36
2

*args, **kwargs & Argument Unpacking

*args collects extra positional arguments into a tuple, **kwargs collects extra keyword arguments into a dict — and the same stars unpack sequences/dicts INTO calls.

  • Signature: def f(pos, *args, kw_only=None, **kwargs) — that exact order
  • *args is a tuple; **kwargs is a dict
  • f(*seq) and f(**mapping) unpack INTO a call — the mirror image
  • wrapper(*args, **kwargs) is the universal forwarding pattern behind every decorator
*collects positionals, ** collects keywords
def order_summary(customer, *items, express=False, **meta):
    print(customer, "ordered", len(items), "items")
    print("items:", items)          # tuple
    print("express:", express)
    print("meta:", meta)            # dict

order_summary("Asha", "pen", "book", express=True, coupon="NEW10", city="Pune")
# Asha ordered 2 items
# items: ('pen', 'book')
# express: True
# meta: {'coupon': 'NEW10', 'city': 'Pune'}

# The universal pass-through signature (decorators use this)
def log_call(func):
    def wrapper(*args, **kwargs):
        print("calling", func.__name__)
        return func(*args, **kwargs)   # forward everything untouched
    return wrapper
3

Scope, LEGB Rule & Closures

Python resolves names through LEGB — Local, Enclosing, Global, Built-in — and inner functions capture enclosing variables as closures, the mechanism behind decorators.

  • Name lookup order: Local → Enclosing → Global → Built-in (LEGB)
  • Assignment anywhere in a function makes that name local everywhere in it — cause of UnboundLocalError
  • Closures capture variables by reference (cells), not by value
  • nonlocal rebinds an enclosing variable; global rebinds a module variable — both are code smells if frequent
Why count += 1 explodes without global
count = 0                # global

def show():
    print(count)         # OK — reads global (L? no, E? no, G? yes)

def bump_broken():
    count += 1           # UnboundLocalError!
    # assignment makes count LOCAL for the whole function,
    # so count += 1 reads a local that doesn't exist yet

def bump():
    global count         # explicitly rebind the global
    count += 1

bump(); bump()
print(count)             # 2

# Prefer: pass values in, return values out — avoid global state
def bump_pure(c):
    return c + 1
4

Lambda, map, filter & sorted key functions

lambda creates small anonymous functions inline — most powerful as the key= argument to sorted/min/max, and alongside map/filter for quick transformations.

  • lambda = single expression, no statements, returns implicitly
  • key= on sorted/min/max is the highest-value lambda use — tuple keys give multi-level sort
  • Negate numeric keys (-x) for descending within a tuple key
  • Prefer comprehensions over map/filter with lambda; prefer def over named lambdas
key=lambda — Python’s Comparator in one line
students = [
    {"name": "Asha",   "cgpa": 8.7, "year": 3},
    {"name": "Vikram", "cgpa": 9.1, "year": 2},
    {"name": "Neha",   "cgpa": 8.7, "year": 2},
]

# Sort by CGPA descending, then year ascending (tuple key)
ranked = sorted(students, key=lambda s: (-s["cgpa"], s["year"]))
for s in ranked:
    print(s["name"], s["cgpa"], s["year"])
# Vikram 9.1 2 / Neha 8.7 2 / Asha 8.7 3

# Top scorer without sorting the whole list
topper = max(students, key=lambda s: s["cgpa"])

# Sort words by length, ties alphabetically
words = ["go", "python", "java", "ai"]
print(sorted(words, key=lambda w: (len(w), w)))  # ['ai','go','java','python']
Learn this free with Aria, your AI tutor → AiCanCode.org/learn/python