If Python were a brain, control flow would be how it makes decisions.
It’s how we tell our program:
- “If this happens, do that.”
- “Otherwise, do something else.”
- “While this is still true, keep repeating.”
In this post, you’ll learn how to:
- Use
if,elif, andelseto control logic - Work with
forandwhileloops - Combine conditions using boolean logic
- Avoid common beginner mistakes
Let’s walk through everything line by line, example by example.
🧠 What Is Control Flow?
Control flow is simply the order in which your code runs, based on logic and conditions. It’s what makes programs smart, reactive, and dynamic.
Python gives us tools like:
if,elif,else→ to make decisionsfor,while→ to repeat actionsand,or,not→ to combine logic
✅ if, elif, and else: Making Decisions
Python
age = 20
if age < 18:
print("You're a minor.")
elif age == 18:
print("Just became an adult!")
else:
print("You're an adult.")🔍 What’s happening?
- If
ageis less than 18 → it prints line 1 - If not, but
age == 18→ line 2 - Else → fallback line
💡 More Examples
Python
temp = 36.5
if temp > 38:
print("You might have a fever.")
elif temp < 36:
print("You might be cold.")
else:
print("You're doing fine.")Python
password = input("Enter password: ")
if password == "admin123":
print("Access granted.")
else:
print("Wrong password.")Note: Python uses indentation (tabs/spaces) to define blocks. Always indent consistently.
🧮 Boolean Logic in Conditions
Python uses and, or, and not to combine conditions.
Python
age = 21
has_id = True
if age >= 18 and has_id:
print("Entry allowed.")Python
score = 92
if score > 90 or score == 90:
print("Excellent!")Python
is_raining = False
if not is_raining:
print("Go outside!")🔁 for Loop: Repeating Over a Sequence
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")Python
for i in range(5):
print(i)
range(5)gives0, 1, 2, 3, 4
🔁 More for Loop Examples
Python
for num in range(1, 6):
print(num ** 2)Python
sentence = "python"
for letter in sentence:
print(letter.upper())🔄 while Loop: Repeat Until a Condition Fails
Python
count = 1
while count <= 5:
print("Count is:", count)
count += 1🛑 Infinite Loops and Break
Python
while True:
command = input("Type 'exit' to quit: ")
if command == "exit":
breakPython
num = 0
while num < 10:
num += 1
if num == 5:
continue # skip 5
print(num)⚠️ Common Mistakes
| Problem | Cause |
|---|---|
Using = instead of == | = is assignment. == is comparison. |
| Forgetting indentation | Python needs indentation to know what belongs to the if/else block |
| Infinite loop by mistake | Condition never becomes false in while loop |
| Comparing wrong types | Don’t compare a string "5" with an integer 5 |
🧪 Practice: Age Category Checker
Python
age = int(input("Enter your age: "))
if age <= 12:
print("You're a child.")
elif age <= 19:
print("You're a teenager.")
elif age <= 59:
print("You're an adult.")
else:
print("You're a senior citizen.")