Control Flow
Control flow determines how a program executes instructions. Python provides tools like conditional statements, loops, and control flow keywords to guide the flow of a program. Understanding control flow helps you write programs that can make decisions and repeat tasks.
Types of Control Flow in Python
- Conditional Statements: Making decisions based on conditions.
- Loops: Repeating a block of code multiple times.
- Control Flow Keywords: Changing the behavior of loops and functions.
1. Conditional Statements
Conditional statements allow you to execute code only if a specific condition is true.
Syntax of if Statement
if condition:
# Code to execute if the condition is True
Examples
1. Simple if Statement
age = 18 if age >= 18: print("You are an adult.")
2. if-else Statement
age = 16 if age >= 18: print("You are an adult.") else: print("You are a minor.")
3. if-elif-else Statement
score = 85 if score >= 90: print("Grade: A") elif score >= 75: print("Grade: B") else: print("Grade: C")
2. Loops
Loops allow you to repeat a block of code multiple times.
Types of Loops
- for Loop: Used for iterating over a sequence (like lists, strings, or ranges).
- while Loop: Repeats as long as a condition is true.
Examples
1. for Loop
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
2. for Loop with range()
for i in range(5): print(i) # Outputs 0 to 4
3. while Loop
count = 0 while count < 5: print(count) count += 1
3. Control Flow Keywords
These keywords give you more control over loops and other flow structures.
1. break
Exits the loop completely.
for i in range(10): if i == 5: break # Stops the loop when i equals 5 print(i)
2. continue
Skips the current iteration and moves to the next.
for i in range(5): if i == 2: continue # Skips the rest of the code for this iteration print(i)
3. pass
A placeholder that does nothing.
for i in range(5): if i == 2: pass # Does nothing print(i)
4. else with Loops
Runs after the loop finishes, unless the loop is exited using break.
for i in range(5): print(i) else: print("Loop completed.")
5. return
Exits a function and optionally returns a value.
def add(a, b): return a + b # Ends the function and returns the sum
Using Nested Control Flow
You can nest control flow structures within each other to create more complex logic.
Example: Nested if inside a Loop
numbers = [1, 2, 3, 4, 5] for num in numbers: if num % 2 == 0: print(f"{num} is even.") else: print(f"{num} is odd.")
match Statement in Python
The match statement, introduced in Python 3.10, is a powerful pattern matching feature used to compare a value against a series of patterns. It's similar to the switch or case statement in other languages but much more advanced and versatile.
Example
def match_color(color): match color: case "red": print("Stop!") case "green": print("Go!") case "yellow": print("Caution!") case _: print("Invalid color.") match_color("green") # Output: Go! match_color("blue") # Output: Invalid color.