What is Control Flow in Python?
Control flow in Python determines the order in which statements are executed. It allows programs to make decisions, repeat tasks, and branch logic based on conditions. The key components of control flow in Python are:
- Conditional Statements (
if
,elif
,else
) - Loops (
for
,while
) - Control Flow Tools (
break
,continue
,pass
)
Conditional Statements in Python
Overview:
Conditional statements allow the program to execute specific blocks of code based on conditions.
Syntax:
if condition:
# Code block 1
elif another_condition:
# Code block 2
else:
# Code block 3
Example:
age = 20
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just became an adult!")
else:
print("You are an adult.")
Output
You are an adult.
Loops in Python
Loops repeat a block of code as long as a condition is true. Python offers two types of loops: for
and while
.
A. for
Loop
The for
loop iterates over a sequence (e.g., list, string, range).
Syntax:
for item in sequence:
# Code block
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")
Output:
I like apple.
I like banana.
I like cherry.
Using range()
in a for
Loop:
for i in range(5):
print(i)
Output:
0
1
2
3
4
B. while
Loop
The while
loop executes a block of code as long as a condition is true.
Syntax:
while condition:
# Code block
Example
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
Output
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Control Flow Tools
Python provides tools to manage loops and conditions effectively.
A. break
Statement
- Exits the loop prematurely.
Example:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
B. continue
Statement
- Skips the rest of the code in the loop for the current iteration.
Example:
for i in range(3):
if i == 1:
pass # Placeholder
print(i)
Output:
for i in range(3):
if i == 1:
pass # Placeholder
print(i)
Best Practices for Control Flow in Python
Use Descriptive Conditions:
- Write clear and meaningful conditions to improve readability.
if age > 18: # Clear condition
Avoid Deep Nesting:
- Refactor deeply nested
if
statements into simpler logic or functions.
- Refactor deeply nested
Use
break
andcontinue
Sparingly:- Overusing them can make code harder to follow.
Leverage
else
with Loops:- Use
else
after loops to run code if nobreak
was encountered.
- Use
for i in range(5):
if i == 3:
break
else:
print("No break encountered.")
Test Edge Cases:
- Test your control flow logic for all possible conditions.
Comment Complex Logic:
- Add comments to explain the intent of complex conditions or loops.
Practice Exercise
Task: FizzBuzz Problem
Write a program that prints numbers from 1 to 20. For multiples of 3, print “Fizz”; for multiples of 5, print “Buzz”; for multiples of both, print “FizzBuzz.”
Solution:
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz