Control flow statements in Python determine the order in which code executes. By mastering them, you can make your programs dynamic, logical, and interactive.
In this guide, we’ll explore decision-making statements, loops, and control keywords with structured examples, actionable tips, and recommended tools.
1. Introduction to Control Flow in Python
Control flow allows your program to decide:
- Which code block to execute
- How many times to repeat a task
- When to stop execution
2. Decision-Making Statements (Conditional Statements)
2.1 if Statement
Executes a block if the condition is True.
Syntax:
if condition:
# code block
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
2.2 if-else Statement
Executes one block if the condition is True, otherwise another block.
Example:
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
2.3 if-elif-else Statement
Checks multiple conditions in sequence.
Example:
marks = 80
if marks >= 95:
print("Grade: A+")
elif marks >= 76:
print("Grade: A")
else:
print("Grade: B")
Actionable Tip:
Keep your conditions clear and avoid overlapping ranges to prevent logic errors.
3. Looping Statements
3.1 for Loop
Used to iterate over a sequence.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3.2 while Loop
Repeats until a condition becomes False.
Example:
count = 1
while count <= 5:
print(count)
count += 1
Best Practice:
Ensure your while loops have a terminating condition to avoid infinite loops.
4. Control Flow Keywords
4.1 break
Terminates the loop prematurely.
Example:
for num in range(1, 10):
if num == 5:
break
print(num)
4.2 continue
Skips the current iteration and moves to the next.
Example:
for num in range(1, 6):
if num == 3:
continue
print(num)
4.3 pass
Does nothing; used as a placeholder.
Example:
for num in range(1, 4):
pass
Actionable Tip:
Use pass when defining structures or loops that you plan to implement later.
5. Nested Control Flow
Control flow statements can be nested for complex logic.
Example:
for i in range(1, 4):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
6. Best Practices for Control Flow
Use descriptive variable names for clarity.
Avoid deep nesting by breaking logic into functions.
Keep loop conditions simple and easy to read.
Use break and continue judiciously for better readability.
Conclusion
Control flow statements are essential for guiding program logic in Python. By mastering conditionals, loops, and control keywords, you can make your code more efficient and maintainable.