← Lesson
BitWithBite
Python · Quick Reference

Lesson 10 — Functions Cheat Sheet

Python
In one line: A function is a named, reusable block of code that performs a specific task. Without functions, every time you need to calculate a grade or validate a password, you'd copy-paste...

Key Ideas

1Why Functions?. A function is a named, reusable block of code that performs a specific task. Without functions, every time you need to calculate a grade or validate a password, you'd ...
2Parameters & Arguments. Parameters are the variable names in the function definition. Arguments are the actual values you pass when calling the function. Python has four parameter types — eac...
3Return Values. The return statement sends a value back to the caller and immediately exits the function. A function can return any Python object — a number, string, list, dict, tuple...
4Variable Scope — The LEGB Rule. When Python encounters a variable name, it searches for it in a specific order of scopes. This order is called the LEGB rule — Local → Enclosing → Global → Built-in.
5Lambda Functions & Higher-Order Functions. A lambda is a small anonymous function written in one line. It's syntactic sugar for a simple function — useful when you need a short function as an argument to anothe...

Code Examples

# Without functions — repeated code (bad) tax1 = 1500 * 0.17 tax2 = 2800 * 0.17 tax3 = 950 * 0.17 # With a function — write once, use anywhere (DRY) def calculate_tax(amount): """Calculate 17% sales tax on an amount.""" return amount * 0.17 tax1 ...
# ── Positional and default parameters ──────── def describe_student(name, age, city="Lahore", grade="A"): return f"{name}, {age}, from {city}, Grade {grade}" print(describe_student("Ali", 20)) # uses defaults print(describe_student(...
# Single return value def square(n): return n ** 2 print(square(7)) # 49 # Early return — guard clause pattern def divide(a, b): if b == 0: return None # exit early on bad input return a / b print(divide(10, 2)) # 5.0 print(div...