Python Control Flow
Python Control Flow
Section titled “Python Control Flow”Control Flow allows program to make decisions, execute different code paths based on data, and handle complex logic.
1. if, else Conditional Statement
Section titled “1. if, else Conditional Statement”It is a block of code that only runs if a specific condition is met. Think of it like a fork in the road: “If the traffic light is red, stop. Otherwise, go.”
2. The if Statement
Section titled “2. The if Statement”The simplest form. If the condition evaluates to True, the code inside the block executes. If False, it is skipped.
if condition: # Code to run if True (Must be indented)age = 20if age >= 18: print("Access Granted") # Runs because 20 >= 18 is True3. The if-else Block
Section titled “3. The if-else Block”Handles the “No” scenario. If the condition is True, do Task A. If False, do Task B.
temperature = 15
if temperature > 20: print("It's warm outside.")else: print("Wear a jacket.") # Runs because 15 is not > 20> All code belonging to the if block must be indented by 4 spaces (or 1 tab).
4. The if-elif-else Ladder
Section titled “4. The if-elif-else Ladder”Used when you have more than two possible outcomes. elif stands for “Else If”.
-
Python checks conditions from top to bottom.
-
As soon as one condition is True, Python runs that block and skips the rest.
score = 85
if score >= 90: print("Grade: A")elif score >= 80: print("Grade: B") # This runs. Python stops checking here.elif score >= 70: print("Grade: C") # Skipped, even though 85 > 70.else: print("Fail")5. Nested if Statements
Section titled “5. Nested if Statements”You can put an if inside another if for hierarchical decisions.
num = 10
if num >= 0: if num == 0: print("Number is Zero") else: print("Positive Number")else: print("Negative Number")6. The Ternary Operator - One-Liner
Section titled “6. The Ternary Operator - One-Liner”A shorthand way to write simple if-else statements. Great for assigning variables concisely.
Syntax: value_if_true if condition else value_if_false
age = 20
# Professional One-Linerstatus = "Adult" if age >= 18 else "Minor"print(status)7. Truthy & Falsy Logic
Section titled “7. Truthy & Falsy Logic”You don’t need to write if len(list) > 0. Python allows you to check objects directly.
-
Falsy Values (Count as False): 0, 0.0, “” (Empty String), [] (Empty List), None, False.
-
Truthy Values (Count as True): Everything else.
my_list = []
# Pythonic Checkif not my_list: print("List is empty") # This runs because [] is Falsy8. Grouping Logic with Parentheses
Section titled “8. Grouping Logic with Parentheses”When mixing and / or, the order of operations can get confusing. Always use parentheses () to group logic explicitly. This prevents bugs.
is_admin = Falseis_member = Truehas_paid = False
# Clear Logic: Admin gets in OR (Member who has paid) gets in.if is_admin or (is_member and has_paid): print("Access Granted")9. Match Case match case
Section titled “9. Match Case match case”The match statement is a powerful upgrade to the traditional “Switch Case” found in other languages. It performs **Structural Pattern Matching **checking not just values, but the shape of the data.
Replaces long chains of if-elif-elif.
status = 404
match status: case 200: print("Success") case 404: print("Not Found") case 500: print("Server Error") case _: print("Unknown Status") # The '_' acts as the 'else' (Default)10. Advanced Pattern Matching
Section titled “10. Advanced Pattern Matching”The match statement can unpack lists and tuples instantly.
# A command systemcommand = ["move", 10, 5]
match command: case ["start"]: print("System Starting...")
case ["move", x, y]: # Matches a list with exactly "move" and two numbers print(f"Moving to X:{x}, Y:{y}")
case ["stop"]: print("Stopping")
case _: print("Invalid Command")11. The OR Pattern (|) & Guards
Section titled “11. The OR Pattern (|) & Guards”-
Pipe (|): Matches multiple options.
-
Guard (if): Adds logic inside the match.
num = 10
match num: case 1 | 2 | 3: print("Small Number (1-3)") case x if x > 100: print("Huge Number") case _: print("Regular Number")Python Loops
Section titled “Python Loops”Loops allow you to run a block of code multiple times without rewriting it. Whether you need to process 10 items or 10 million, loops make it possible.
A loop is a control structure that repeats a block of code as long as a specific condition is met.
-
For Loop: Used when you know how many times you need to repeat (e.g., “Do this for every student in the class”).
-
While Loop: Used when you don’t know how many times, but you know the stop condition (e.g., “Keep running until the battery dies”).
The range() Function
Section titled “The range() Function”Before using loops, you must understand range(). It generates a sequence of numbers and is the engine behind most loops.
-
Syntax: range(start, stop, step)
-
Crucial Rule: The stop number is excluded.
# 1. Basic (0 to stop-1)print(list(range(5))) # Output: [0, 1, 2, 3, 4]
# 2. Start and Stopprint(list(range(2, 6))) # Output: [2, 3, 4, 5]
# 3. Steps (Skipping numbers)print(list(range(0, 10, 2))) # Output: [0, 2, 4, 6, 8]1. The for Loop
Section titled “1. The for Loop”The for loop is used to iterate over a Sequence (like a List, Tuple, String, or Dictionary). It is safer than while because it automatically stops when it reaches the end of the sequence.
Syntax:
for item in sequence: # Do something with itemIterating over different data types
Section titled “Iterating over different data types”# 1. Listfruits = ["Apple", "Banana"]for fruit in fruits: print(fruit)
# 2. String (Character by Character)for char in "Python": print(char)
# 3. Using Range (Counting)for i in range(3): print(f"Iteration {i}")2. The while Loop
Section titled “2. The while Loop”The while loop keeps running as long as the condition is True.
- If the condition never becomes False, you create an Infinite Loop (which crashes your program).
Syntax:
while condition: # Code to repeat # Important: Update variables to eventually end the loop!Example:
battery = 3while battery > 0: print(f"Phone is on. Battery: {battery}%") battery -= 1 # Decrease battery (Critical Step!)
print("Phone died.")The while-else Block
Section titled “The while-else Block”A unique Python feature. The else block runs once when the loop finishes normally (i.e., the condition becomes False).
- *Note: If you stop the loop abruptly using *break, the else block is SKIPPED.
x = 0while x < 3: print(x) x += 1else: print("Loop finished successfully without break.")4. Loop Control Statements
Section titled “4. Loop Control Statements”Sometimes you need to interrupt the standard flow of a loop.
KeywordDescriptionAnalogybreakStops the loop entirely and exits.“Emergency Stop Button”continueSkips the current iteration and moves to the next one.“Skip this song”passDoes nothing. Used as a placeholder.“I’ll do this later”
1. The break Statement
Section titled “1. The break Statement”Stops the loop immediately, even if the condition is still True.
# Stop searching when we find "Target"items = ["Book", "Pen", "Target", "Pencil"]
for item in items: if item == "Target": print("Found it!") break # Exit loop immediately print(f"Checking {item}...")2. The continue Statement
Section titled “2. The continue Statement”Jumps back to the top of the loop for the next round, ignoring any code below it.
# Print only odd numbersfor i in range(5): if i % 2 == 0: continue # Skip even numbers print(i) # This only runs for 1, 33. The pass Statement
Section titled “3. The pass Statement”Loops cannot be empty. If you are structuring code but haven’t written the logic yet, use pass.
for x in [1, 2, 3]: pass # To be implemented later (No Error)5.Nested Loops
Section titled “5.Nested Loops”A loop inside another loop. This is commonly used for working with grids, matrices, or combinations.
Logic: For every one iteration of the Outer Loop, the Inner Loop runs completely.
colors = ["Red", "Blue"]items = ["Car", "Bike"]
for color in colors: # Outer Loop for item in items: # Inner Loop print(color, item)
# Output:# Red Car# Red Bike# Blue Car# Blue Bike6. Comprehensions
Section titled “6. Comprehensions”Comprehensions allow you to create lists, dictionaries, or sets in a single, concise line. They are often faster than traditional loops.
List Comprehension
Section titled “List Comprehension”Syntax: [expression for item in iterable if condition]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# Goal: Create a list of fruits containing "a"# Traditional Way (4 lines)# newlist = []# for x in fruits:# if "a" in x:# newlist.append(x)
# The Pro Way (1 line)newlist = [x for x in fruits if "a" in x]print(newlist) # ['apple', 'banana', 'mango']Dictionary & Set Comprehensions
Section titled “Dictionary & Set Comprehensions”Same logic, different brackets.
# Dictionary: {Name: Length}names = ["Alice", "Bob"]lengths = {name: len(name) for name in names} # {'Alice': 5, 'Bob': 3}
# Set: Unique Squaresnums = [1, 1, 2, 2]squares = {x**2 for x in nums} # {1, 4}7. enumerate() (Tracking Index)
Section titled “7. enumerate() (Tracking Index)”Beginners often create a separate counter variable (i = 0) to track the index. Don’t do this. Use enumerate() to get both the index and value instantly.
names = ["Alice", "Bob", "Charlie"]
# Professional Wayfor index, name in enumerate(names): print(f"User {index}: {name}")8. zip() (Looping Two Lists)
Section titled “8. zip() (Looping Two Lists)”If you need to loop through two lists at the same time, use zip().
names = ["Alice", "Bob"]ages = [25, 30]
for name, age in zip(names, ages): print(f"{name} is {age} years old.")9. Infinite Loops - Intentional
Section titled “9. Infinite Loops - Intentional”Sometimes (like in game servers or chatbots), you want a loop to run forever until a user stops it.
while True: command = input("Type 'exit' to stop: ") if command == 'exit': break print(f"You typed: {command}")10. else in Loops
Section titled “10. else in Loops”The else block in a for loop runs only if the loop completed without hitting a break.
numbers = [1, 3, 5, 7]
for n in numbers: if n == 4: print("Found 4!") breakelse: # This runs because 'break' was never hit print("4 was not found in the list.")11. How Loops Actually Work - Iterators
Section titled “11. How Loops Actually Work - Iterators”Why can you loop through a List but not an Integer? Because Lists are Iterable.
-
Iterable: An object capable of returning its members one by one.
-
Iterator: The agent that actually fetches the next item.
When you run a for loop, Python secretly does this:
-
Calls iter(object) to get an iterator.
-
Calls next(iterator) repeatedly to get items.
-
Stops when it hits a StopIteration error.
12. Generators - Memory Optimization
Section titled “12. Generators - Memory Optimization”List Comprehensions [] create the entire list in memory immediately. If the list has 1 billion items, your computer crashes. Generator Expressions () produce items one by one, using almost zero memory.
import sys
# List Comprehension (Greedy - Allocates memory for ALL numbers)heavy_list = [x**2 for x in range(10000)]print(sys.getsizeof(heavy_list)) # ~87,000 bytes
# Generator Expression (Lazy - Generates on demand)light_gen = (x**2 for x in range(10000))print(sys.getsizeof(light_gen)) # ~100 bytes (Tiny!)- Use Generators for large datasets or file processing.