Why This Topic Matters
So far we have learned how to store data with variables and group it with collections. But a program is not just data sitting there. It needs to make decisions and repeat actions. That is exactly what if, for and while do.
By the end of this post you will know:
- How to make decisions in code with
if,elifandelse - How to repeat an action with
forandwhile - How to control a loop with
break,continueand the loopelse - Which loop to pick for which situation
1. Conditions: if, elif, else
1.1 What is a Condition?
A condition is a statement that runs only when something is True.
Every condition is built on a comparison, something that evaluates to True or False (a bool, as we saw in the data types post).
Simple Example
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
# Adult
Notice the indentation. Python uses spaces (4 is standard) to decide what belongs inside the if block. This is not just style, it is a rule. Wrong indentation causes an IndentationError.
1.2 Multiple Conditions with elif
Use elif ("else if") to check more than one condition in order:
marks = 75
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "D"
print(grade) # B
Python checks each condition from top to bottom and stops at the first one that is True. Since marks is 75, it does not even look at the marks >= 90 line result, it jumps straight to marks >= 75, which is true, sets the grade, and skips the rest.
1.3 Combining Conditions
Use and, or and not to combine more than one condition:
x = 10
print(x > 5 and x < 20) # True both must be true
print(x > 5 or x < 2) # True at least one must be true
print(not (x > 5)) # False flips True to False
Comparison operators, quick reference
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
>, < | greater than, less than |
>=, <= | greater than or equal to, less than or equal to |
2. The for Loop
2.1 What is it?
A for loop goes through each item of a collection, one at a time.
Use a for loop when you know what you are looping over, a list, a range of numbers, or any other collection.
Simple Example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
On each round, the loop variable (fruit here) is set to the next item, until there are no items left.
2.2 Looping with range()
To repeat something a fixed number of times, use range(). It generates a sequence of numbers without you having to write them out.
for i in range(5):
print(i, end=" ")
# 0 1 2 3 4
print()
for i in range(2, 10, 2): # start, stop, step
print(i, end=" ")
# 2 4 6 8
print()
for i in range(5, 0, -1): # counting down
print(i, end=" ")
# 5 4 3 2 1
range(5) starts at 0 and goes up to, but not including, 5. When you give three numbers, they mean start, stop and step, and a negative step counts down.
2.3 Getting the Position Too, with enumerate()
for i, fruit in enumerate(["a", "b", "c"]):
print(i, fruit)
# 0 a
# 1 b
# 2 c
enumerate() gives you both the position and the item, so you do not need to manage a counter variable yourself.
2.4 A Running Total
total = 0
for n in [1, 2, 3, 4, 5]:
total += n # same as total = total + n
print(total) # 15
3. The while Loop
3.1 What is it?
A while loop keeps repeating as long as a condition stays True.
Use a while loop when you do not know in advance how many times you need to repeat, only the condition that should stop it.
Simple Example
count = 0
while count < 5:
print(count, end=" ")
count += 1
# 0 1 2 3 4
Three things must be true for a while loop to behave correctly: a starting value (count = 0), a condition (count < 5), and something inside the loop that eventually makes the condition false (count += 1). Forget the last part, and the loop never stops, this is called an infinite loop.
3.2 Example: Factorial
n = 5
fact = 1
while n > 0:
fact *= n
n -= 1
print(fact) # 120
3.3 while True and break
Sometimes it is cleaner to loop forever and use break to stop when you are ready:
i = 0
while True:
if i >= 3:
break
print("loop", i)
i += 1
# loop 0
# loop 1
# loop 2
4. Controlling a Loop: break, continue, else
4.1 break, Stop the Loop Completely
for i in range(10):
if i == 5:
break
print(i, end=" ")
# 0 1 2 3 4
As soon as i reaches 5, the loop stops entirely, even though range(10) had more numbers left.
4.2 continue, Skip Just This Round
for i in range(5):
if i % 2 == 0:
continue
print(i, end=" ")
# 1 3
continue skips the rest of the current round and jumps straight to the next one. Here, every even number gets skipped, so only the odd numbers get printed.
4.3 The Loop else, an Underused Feature
Both for and while loops can have an else block. It runs only if the loop finished normally, without hitting a break.
for i in range(3):
print(i)
else:
print("done")
# 0
# 1
# 2
# done
for i in range(10):
if i == 3:
break
print(i)
else:
print("not printed")
# 0
# 1
# 2
# (else does NOT run, because break happened)
This is useful for search-style logic: "did I find what I was looking for, or did I go through the whole list without success?"
tries = ["xyz", "123", "abc"]
password = "abc"
attempts = 0
idx = 0
while attempts < 3:
entered = tries[idx]
idx += 1
attempts += 1
if entered == password:
print("Correct")
break
else:
print("Locked out")
# Correct
5. Nested Loops
A loop can sit inside another loop. The inner loop finishes completely for every single round of the outer loop.
for i in range(3):
for j in range(3):
print(i, j, end=" | ")
# 0 0 | 0 1 | 0 2 | 1 0 | 1 1 | 1 2 | 2 0 | 2 1 | 2 2 |
This pattern is common when working with grids, tables, or comparing every item in one list against every item in another.
6. for vs while: Which One to Use
| Situation | Use |
|---|---|
| You know the collection or the count of repeats in advance | for |
| You are looping over items in a list, string, or other collection | for |
| You are repeating until some condition becomes true, and you do not know how many rounds it will take | while |
| You are waiting for user input to be valid, or a retry limit | while |
A simple way to decide: if you can say "repeat this for every item in X", reach for for. If you can only say "keep repeating until X happens", reach for while.
7. A Shortcut: List Comprehension
Once you are comfortable with for and if, Python gives you a shorter way to build a list in one line:
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens) # [2, 4, 6]
squares = [n * n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]
This does exactly the same thing as a normal loop that builds a list with .append(), but in one line. It is worth knowing how to read, even before you start writing your own.
8. Practical Examples
Example 1: Grading Students
students = [
{"name": "A", "marks": 92},
{"name": "B", "marks": 68},
{"name": "C", "marks": 40}
]
for s in students:
if s["marks"] >= 90:
grade = "A"
elif s["marks"] >= 60:
grade = "B"
else:
grade = "Fail"
print(f"{s['name']}: {grade}")
# A: A
# B: B
# C: Fail
Example 2: Sum of Even Numbers Only
total = 0
for n in range(1, 11):
if n % 2 != 0:
continue
total += n
print(total) # 30
Example 3: Simple Login Retry
correct_password = "python123"
attempts = 0
max_attempts = 3
while attempts < max_attempts:
entered = input("Enter password: ")
attempts += 1
if entered == correct_password:
print("Login successful")
break
print(f"Wrong password. {max_attempts - attempts} attempts left")
else:
print("Account locked")
9. Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
Wrong indentation inside if or a loop | IndentationError | Use consistent spaces (4 is standard) for every block |
Forgetting to update the loop variable in a while loop | Infinite loop, program never stops | Make sure something inside the loop moves it toward the stop condition |
Using = instead of == in a condition | SyntaxError | = assigns a value, == compares two values |
Expecting the loop else to run after a break | It is silently skipped | Remember: else only runs if the loop finished without a break |
Using break in a nested loop expecting it to stop both loops | Only the inner loop stops | Use a flag variable, or put the loops in a function and return |
Quick Recap
| You need | Use |
|---|---|
| To run code only when something is true | if, elif, else |
| To repeat over a known collection or count | for |
| To repeat until a condition becomes true | while |
| To stop a loop early | break |
| To skip just this round of a loop | continue |
| To run code only if a loop finished without a break | loop else |
if, for and while are the building blocks that make a program actually do something with the data it holds. Almost every program you write, from a small script to a full ML pipeline, is built on some combination of these three.
Practice Questions
- What does
range(3, 12, 3)produce? - What is the difference between
breakandcontinue? - Write the condition that checks if a number
nis between 10 and 20, including both ends. - Why can a
while Trueloop be dangerous if you forget thebreak? - Does the loop
elserun if the loop finishes normally, with nobreak?
Click to reveal answers
3, 6, 9, since it starts at 3, stops before 12, and steps by 3.breakstops the loop completely.continueskips only the current round and moves to the next one.n >= 10 and n <= 20- It repeats forever with no way to stop, freezing the program, unless something inside eventually calls
break. - Yes, the loop
elseruns whenever the loop completes without hitting abreak.