Python Control Flow Explained — Conditionals and Loops Step-by-Step
Control flow is how Python programs make decisions and repeat actions. Every programming language uses these same concepts — learn them once and you’ll recognize them everywhere.
What You’ll Learn
- How
if/elif/elseconditionals work and when to use each - The difference between
forloops andwhileloops - How to control loops with
breakandcontinue - Real-world patterns like
zip,enumerate, and list comprehensions - Common control flow mistakes and how to avoid them
Why Control Flow Matters
Control flow is what makes programs intelligent. Without it, your code runs top to bottom, every time, the same way. With conditionals, your program can react differently based on user input, file contents, or system state. Durga Antivirus Pro uses control flow to decide if a file is safe — if the signature matches a known threat, block it; if the behavior pattern is suspicious, quarantine it; otherwise, let it through. DodaZIP uses loops to process hundreds of files in a directory. Every useful program needs control flow.
flowchart LR
A["Python Basics"] --> B["Control Flow"]
B --> C["Functions"]
C --> D["Lists & Dicts"]
D --> E["Modules & Packages"]
E --> F["File I/O & Errors"]
A:::done --> B:::current --> C
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#2563eb,stroke:#2563eb,color:#fff
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
style F fill:#f1f5f9,stroke:#94a3b8,color:#64748b
Conditionals — Making Decisions
Think of conditionals like a fork in the road. You reach a point where you must choose one path or another based on a condition. Does the user have permission? Is the file too large? Is the sensor reading above the threshold?
How if / elif / else Works
flowchart TD
Start["Program reaches<br/>conditional"] --> Cond{"Condition<br/>is True?"}
Cond -->|"Yes"| If["Execute<br/>if block"]
Cond -->|"No"| Elif{"elif condition<br/>is True?"}
Elif -->|"Yes"| ElifBlock["Execute<br/>elif block"]
Elif -->|"No"| Else["Execute<br/>else block"]
If --> After["Continue after<br/>conditional"]
ElifBlock --> After
Else --> After
style Start fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
style Cond fill:#fef3c7,stroke:#f59e0b,color:#78350f
style Elif fill:#fef3c7,stroke:#f59e0b,color:#78350f
style If fill:#d1fae5,stroke:#10b981,color:#064e3b
style ElifBlock fill:#d1fae5,stroke:#10b981,color:#064e3b
style Else fill:#fce7f3,stroke:#ec4899,color:#831843
Only one block executes. Python checks from top to bottom and runs the first matching condition:
score = 85
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: BLet’s trace this: score is 85. Python asks “is score >= 90?” → No. “Is score >= 75?” → Yes. It assigns grade = "B", then skips everything else. If score were 50, both first conditions fail, and else gives us "F".
{ }. Always be consistent — mixing spaces and tabs causes IndentationError!Ternary (Conditional Expression)
For simple if/else, you can write it in one line:
age = 20
can_vote = "Yes" if age >= 18 else "No"
print(can_vote) # "Yes"This is shorthand for:
if age >= 18:
can_vote = "Yes"
else:
can_vote = "No"Use the ternary form only for simple, single-condition checks. If you have multiple conditions, use a full if/elif/else for clarity.
Match Statement (Python 3.10+)
The match statement is like a switch in other languages. Think of it as a multi-way fork:
day = 3
match day:
case 1: name = "Monday"
case 2: name = "Tuesday"
case 3: name = "Wednesday"
case 4: name = "Thursday"
case 5: name = "Friday"
case _: name = "Weekend" # Default case
print(name) # "Wednesday"Loops — Repeating Actions
Imagine you need to check 100 files for malware. Writing the same check 100 times would be absurd. That’s where loops come in — they let you run the same code block multiple times.
for Loops — Iterate Over Sequences
A for loop goes through each item in a collection, one at a time. Think of it like going through a shopping list — you look at item 1, do something with it, then item 2, then item 3, until you’ve processed everything.
flowchart TD
Start["for fruit in fruits:"] --> Check{"More items<br/>in list?"}
Check -->|"Yes"| Get["Get next item<br/>apple → banana → cherry"]
Get --> Body["Execute loop body<br/>print(fruit)"]
Body --> Check
Check -->|"No"| End["Continue after loop"]
style Start fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
style Check fill:#fef3c7,stroke:#f59e0b,color:#78350f
style Body fill:#d1fae5,stroke:#10b981,color:#064e3b
style End fill:#fce7f3,stroke:#ec4899,color:#831843
# Over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output: apple, banana, cherryEach iteration: Python takes the next item from fruits, assigns it to fruit, runs the print statement, then moves to the next item until there are no more.
Using range() — Generate Number Sequences
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(1, 10, 2): # 1, 3, 5, 7, 9 (step=2)
print(i)range(5) means “start at 0, stop before 5”. This zero-based counting is consistent with how list indices work — the first element is at position 0.
enumerate() — Get Index and Value Together
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherrywhile Loops — Run While Condition is True
A while loop is like a bouncer at a club — as long as you meet the condition (age >= 21), you keep going in. The moment the condition becomes false, you stop.
flowchart TD
Start["Initialize<br/>count = 1"] --> Check{"count <= 5?"}
Check -->|"True"| Body["Execute body<br/>print(count)"]
Body --> Update["Update variable<br/>count += 1"]
Update --> Check
Check -->|"False"| End["Continue after loop"]
count = 1
while count <= 5:
print(count)
count += 1
# 1, 2, 3, 4, 5False, the loop runs forever. Always make sure your variable updates toward the exit condition. Imagine a bouncer who never checks ID — the line never stops moving.break and continue — Fine Control
break— exit the loop immediately (like an emergency exit)continue— skip the rest of this iteration and move to the next (like skipping a song on a playlist)
for i in range(1, 11):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
# Output: 1, 2, 4, 5, 6
flowchart TD
Loop["for i in range(1, 11):"] --> C1{"i == 3?"}
C1 -->|"Yes"| Skip["continue → skip to next i"]
C1 -->|"No"| C2{"i == 7?"}
C2 -->|"Yes"| Stop["break → exit loop"]
C2 -->|"No"| Print["print(i)"]
Print --> Loop
Skip --> Loop
Useful Patterns
# Loop over two lists together (zip)
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Loop over dictionary
person = {"name": "Alice", "age": 25, "role": "dev"}
for key, value in person.items():
print(f"{key} = {value}")
# List comprehension (shorthand for loops)
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Common Mistakes
1. Forgetting the Colon
# Wrong — missing colon
if score > 50
print("Pass")
# Right
if score > 50:
print("Pass")Every if, elif, else, for, while, def, and class statement needs a colon :.
2. Inconsistent Indentation
# Wrong — mixed tabs and spaces
if True:
print("Hello")
print("World") # IndentationError!
# Right — use 4 spaces consistently
if True:
print("Hello")
print("World")3. Infinite While Loop
# Wrong — x never changes
x = 1
while x < 10:
print(x)
# forgot: x += 1
# Right
x = 1
while x < 10:
print(x)
x += 14. Modifying a List While Iterating
# Wrong — skips items
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n % 2 == 0:
numbers.remove(n) # Skips elements!
print(numbers) # [1, 3, 5] — actually wrong output
# Right — iterate over a copy
for n in numbers[:]: # [:] makes a copy
if n % 2 == 0:
numbers.remove(n)5. Using = Instead of == in Conditions
# Wrong — assigns 5 to x, always True
if x = 5:
print("x is 5")
# Right — compares
if x == 5:
print("x is 5")6. Forgetting That range(5) Goes 0-4, Not 1-5
This is the #1 confusion for beginners. Python uses zero-based indexing. range(5) = 0, 1, 2, 3, 4. Use range(1, 6) for 1 through 5.
Practice Questions
1. What does this code print?
for i in range(3):
print(i * 2)0, 2, 4. For i=0: 0×2=0. i=1: 1×2=2. i=2: 2×2=4.
2. Fix this code that intends to print numbers 1-5:
count = 1
while count <= 5:
print(count)This never increments count — infinite loop. Fix: add count += 1 inside the loop.
3. What’s the difference between break and continue?
break exits the loop entirely. continue skips the current iteration and moves to the next one.
4. Write a loop that prints only the even numbers from 1 to 10.
for i in range(1, 11):
if i % 2 == 0:
print(i)5. What does this output?
for i in range(5):
if i == 2:
continue
if i == 4:
break
print(i)0, 1, 3. When i=2, continue skips printing. When i=4, break exits before printing.
Challenge: Write FizzBuzz — print numbers 1 to 20. For multiples of 3, print “Fizz” instead. For multiples of 5, print “Buzz”. For multiples of both, print “FizzBuzz”.
Solution
for i in range(1, 21):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)FAQ
Try It Yourself
Run this FizzBuzz program to see control flow in action:
# FizzBuzz from 1 to 15
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)Expected output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzWhat’s Next
Now that you control the flow of your programs, learn how to organize code into reusable functions.
| Topic | Description | Link |
|---|---|---|
| Python Functions | Write reusable code blocks | https://tutorials.dodatech.com/programming-languages/python/py-functions/ |
| Python Lists & Dicts | Work with collections | https://tutorials.dodatech.com/programming-languages/python/py-lists-dicts/ |
| JavaScript Control Flow | Compare with another language | JavaScript |
Practice tip: Take the FizzBuzz example and modify the range to print from 1 to 100. Then try writing a number-guessing game where the user has to guess a random number between 1 and 100, with hints like “too high” or “too low”.
What’s Next
Congratulations on completing this Py Control Flow tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro