Control Flow
Control flow refers to the order in which a program’s statements are executed, allowing you to make decisions, repeat actions, or skip code based on conditions. Python provides several control flow structures, such as:
- Conditional Statements
- Loops
- Control Statements
- Exception Handling
1. Conditional Statements
Conditional statements allow you to execute code based on specific conditions. The primary constructs are if, elif, and else.
age = 20
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# Output: Adult
2. Loops
a) While Loop
A while loop repeatedly executes a block of code as long as a specified condition is True.
count = 0
while count < 5:
print(count)
count += 1
# Output: 0 1 2 3 4
Using break:
Exits the loop immediately
count = 0
num = 10
while num > 0:
if num == 5:
break
print(num)
num -= 1
# Output: 10 9 8 7 6
Using continue:
Skips the rest of the current iteration and checks the condition again.
num = 10
while num > 0:
num -= 1
if num % 2 == 0:
continue
print(num)
# Output: 9 7 5 3 1 (skips even numbers)
b) For Loop
A for loop iterates over a sequence (like a list, tuple, string, or range) to execute a block of code for each item.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output: apple banana cherry
3. Loop Control Statements
-
break: Exits the loop
for i in range(10): if i == 5: break print(i) # Output: 0 1 2 3 4 -
continue: Skips current iteration
for i in range(5): if i == 2: continue print(i) # Output: 0 1 3 4 -
pass: Does nothing (placeholder)
for i in range(5): if i == 2: pass print(i) # Output: 0 1 2 3 4
4. Exception Handling (try/except)
Manages errors and exceptional cases.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution completed")
# Output:
# Cannot divide by zero
# Execution completed