if / elif / else
def status_label(status: str) -> str:
status = status.strip().upper()
if status == "DELIVERED":
return "β
revenue"
elif status in ("CANCELLED", "RETURNED"):
return "β lost"
else:
return "β³ pending"
for s in ["DELIVERED", " cancelled ", "PLACED"]:
print(s.strip(), "β", status_label(s))DELIVERED β β revenue cancelled β β lost PLACED β β³ pending
Blocks are defined by indentation. in ("A", "B") checks several values at once. Comparison operators are the same as SQL, except equality is == and not-equal is !=; combine with and, or, not.
for loops, enumerate, zip, continue
products = ["Headphones", "Smartwatch", "Charger"]
prices = [1999, 4999, 499]
for i, product in enumerate(products, start=1): # position + value
print(i, product)
for product, price in zip(products, prices): # walk two lists together
if price < 1000:
continue # skip cheap items
print(f"{product}: βΉ{price}")1 Headphones 2 Smartwatch 3 Charger Headphones: βΉ1999 Smartwatch: βΉ4999
while and break
attempt = 0
while attempt < 3:
attempt += 1
print(f"attempt {attempt}")
if attempt == 2:
print("success, stopping early")
breakattempt 1 attempt 2 success, stopping early
Use while when you don't know the number of repeats in advance (retries, pagination until there's no next page).
Functions
def order_amount(quantity: int, price: float, discount: float = 0.0) -> float:
"""Total for one order line after a discount (0.1 = 10%)."""
return round(quantity * price * (1 - discount), 2)
print(order_amount(3, 499)) # positional arguments
print(order_amount(3, 499, discount=0.1)) # keyword argument
print(order_amount(price=1999, quantity=2)) # any order with keywords1497.0 1347.3 3998.0
- Type hints (
quantity: int,-> float) document inputs and output. - The docstring (first string in the body) explains what it does; editors show it on hover.
- Default values make arguments optional; keyword arguments make calls readable.
def min_max(values: list[float]) -> tuple[float, float]:
return min(values), max(values)
lowest, highest = min_max([1999, 4999, 499, 1299])
print(lowest, highest)499 4999
*args and **kwargs
def log_event(event: str, *tags: str, **fields) -> None:
print(event, tags, fields)
log_event("order_loaded", "bronze", "daily", rows=10, source="orders.csv")order_loaded ('bronze', 'daily') {'rows': 10, 'source': 'orders.csv'}The mutable default trap (interview classic)
def add_tag(tag, tags=[]): # β the SAME list is reused on every call
tags.append(tag)
return tags
print(add_tag("a"))
print(add_tag("b")) # surprise: ['a', 'b']['a'] ['a', 'b']
def add_tag(tag, tags=None): # β
create a new list each call
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("a"))
print(add_tag("b"))['a'] ['b']
lambda, sorted, filter, map
orders = [("O1", 1999), ("O2", 499), ("O3", 4999)]
print(sorted(orders, key=lambda pair: pair[1])) # sort by amount
print(list(filter(lambda pair: pair[1] > 1000, orders)))
print(list(map(lambda pair: pair[0], orders)))[('O2', 499), ('O1', 1999), ('O3', 4999)]
[('O1', 1999), ('O3', 4999)]
['O1', 'O2', 'O3']A lambda is a tiny unnamed function for one expression. For anything longer, write a normal def.
Modules: split code into files
"""Small helpers shared by ShopKart scripts."""
VALID_STATUSES = {"PLACED", "DELIVERED", "CANCELLED", "RETURNED"}
def clean_status(raw: str) -> str:
"""' delivered ' β 'DELIVERED'. Raises ValueError for unknown statuses."""
status = raw.strip().upper()
if status not in VALID_STATUSES:
raise ValueError(f"unknown status: {raw!r}")
return statusfrom shopkart_utils import clean_status, VALID_STATUSES
print(clean_status(" delivered "))
print(sorted(VALID_STATUSES))DELIVERED ['CANCELLED', 'DELIVERED', 'PLACED', 'RETURNED']
Now every script can reuse the same cleaning rule, and you can test it once (lesson 11). Constants in UPPER_CASE signal βdon't change thisβ.
π― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is the difference between a parameter and an argument?Fresher+
Q2Explain the mutable default argument problem.1β3 yrs+
Q3How are arguments passed in Python: by value or by reference?1β3 yrs+
Q4What does if __name__ == '__main__': do?1β3 yrs+
Q5What is a closure?3+ yrs+
Key takeaways
- βControl flow and functions turn one-off code into reusable logic.
- βType hints and docstrings make functions self-explaining.
- βAvoid mutable defaults; keep shared logic in modules.
- βNext: reading and writing CSV and JSON files.
Frequently asked questions
What are *args and **kwargs?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They let a function accept a flexible number of inputs, and are common in decorators and wrappers.
Why is a list as a default argument a bug?
Default values are created once, when the function is defined, so every call shares the same list. Use None as the default and create a new list inside the function.
What are type hints?
Annotations like def amount(quantity: int) -> float. Python doesn't enforce them at run time, but editors and tools like mypy use them to catch mistakes, and they document the function.
What is a module?
Any .py file. Other files import its functions with import or from ... import .... A folder of modules with an __init__.py is a package.
break vs continue?
break leaves the loop entirely; continue skips the rest of this iteration and goes to the next one.
π§ Quick check: functions and control flow
1. enumerate(items, start=1) gives...
2. def f(x, tags=[]) is risky because...
3. zip(products, prices) ...
4. A function without a return statement returns...
Checking your accessβ¦