Loops in Python
Lesson 4 — Repetition & Repeating Code
👨🏫 INSTRUCTOR: CAPTAIN NAJIB HUSSEIN MOHAMED
Python Programming @Copyright By Captain Najib Hussein 20226
What is a Loop?
"If you want something done
Repeat Code 100 times, use a loop."
Run the same block of code
multiple times automatically Without loops,
repetition = writing the
same line over and
Save Time & Effort over.
No need to copy-paste code
100 times — let the loop do
it
Python Programming @Copyright By Captain Najib Hussein 20226
Two Types of Loops in Python
for loop while loop
Repeats a set number of times — ideal when you know how many Keeps running as long as a condition is True — stops when it
iterations you need becomes False
for loop Looping while loop
Python Programming @Copyright By Captain Najib Hussein 20226
For Loop — Syntax
for variable in sequence: 1
# code to repeat
for
Keyword that starts the loop
Indentation matters! The code block inside the loop must be
indented.
variable
Holds the current value each iteration
sequence
What to loop over — a list, range, or string
Python Programming @Copyright By Captain Najib Hussein 20226
Your First For Loop
Code Output
for i in range(5): Hello
print("Hello") Hello
Hello
Hello
range(5) generates Hello
numbers 0, 1, 2, 3, 4 —
that's 5 steps total. Printed exactly 5 times — one
for each number in range(5).
Python Programming @Copyright By Captain Najib Hussein 20226
Print Numbers with range()
Code
1 2
for i in range(5): Starts at 0 Ends at 4
print(i)
Python counts from range(5) stops before 5
zero by default
Output
0 3
1
2 5 total steps
3
0→1→2→3→4
4
Python Programming @Copyright By Captain Najib Hussein 20226
Set a Custom Start & Stop
Code
range(start, stop) — two arguments let you
control exactly where counting begins and ends.
for i in range(1, 6):
print(i)
Start = 1 Stop = 6
Output
First number included Last number excluded
1 — stops at 5
2
3
4
5
Python Programming @Copyright By Captain Najib Hussein 20226
Counting by Steps
Code
range(start, stop, step) — the third argument sets
the jump size between numbers.
for i in range(0, 10, 2):
print(i)
Start = 0 Stop = 10
Output
0 Step = 2
2
Skip every other number
4
6
8
Python Programming @Copyright By Captain Najib Hussein 20226
The While Loop
Code
x = 1
while x <= 5:
print(x)
x += 1
Output Run code
Check x ≤ 5? Update x += 1
block
1
2
3
The while loop keeps running as long as the condition is True. It stops
4
the moment it becomes False.
5
Python Programming @Copyright By Captain Najib Hussein 20226
⚠️ Infinite Loop — Be Careful!
Code
When it happens
while True: Forgetting to update the
print("Hello") condition variable inside the loop
This loop runs forever — it
never stops because the How to stop it
condition is always True.
Press Ctrl + C in the terminal to
force-quit
How to avoid it
Always make sure your condition
can eventually become False
Python Programming @Copyright By Captain Najib Hussein 20226
Python Programming @Copyright By Captain Najib Hussein 2026