By the end of this lesson, you will be able to:
:information_source: Definition: A loop is a programming structure that lets you run the same code multiple times automatically.
Imagine you want to print "Hello" 100 times. Without loops, you'd have to write print("Hello")
100 times! That's a lot of typing and very inefficient.
Loops solve this problem by letting you write the code once and tell Python to repeat it.
Python gives us two powerful types of loops:
A for loop helps you go through each item in a collection (like a list) or repeat something a specific number of times.
:bulb: When to use a for loop:
- You know exactly how many times to repeat
- You want to go through each item in a list
- You need to process each character in a string
for item in sequence:
# Your code here (indented!)
# This runs for each item
:memo: Note The indentation (4 spaces) is very important! It tells Python which code belongs inside the loop.
Figure 6.2 For loop flows:
┌─────────┐
│ Start │
└────┬────┘
│
▼
┌─────────────────┐ If no more items
│ Item from │ in the sequence
│ sequence │───────────────┐
└────────┬────────┘ │
│ │
│ Next item │
│ from sequence │
▼ │
┌─────────────────┐ │
│ Execute │ │
│ Statement(s) │ │
└────────┬────────┘ │
│ │
└────────────────────────┘
│
▼
┌─────┐
│ End │
└─────┘
A while loop keeps running as long as a condition is true. It's like saying "keep doing this while something is happening."
:bulb: When to use a while loop:
- You don't know exactly how many times to repeat
- You want to continue until something specific happens
- You're waiting for user input or a certain result
:warning: Warning Important: Always update your variable inside the loop, or it might run forever!
# Set up your variable first
counter = 0
while condition:
# Your code here
# Don't forget to update your variable!
counter = counter + 1
Figure 6.4 While Loop Flows:
┌─────────┐
│ Start │
└────┬────┘
│
▼
┌─────────────────┐ False
│ While ├───────────┐
│ Condition? │ │
└────────┬────────┘ │
│ True │
▼ │
┌─────────────────┐ │
│ Codes to │ │
│ Execute │ │
└────────┬────────┘ │
│ │
└────────────────────┘
│
▼
┌─────-┐
│ Exit │
└─────-┘
Condition | While Loop | If Statement |
---|---|---|
True | Runs code repeatedly | Runs code once |
False | Stops the loop | Skips the code |
:memo: Note Remember: If statements run once, while loops can run many times!
Python gives us three special tools to control our loops:
The else statement runs special code after your loop finishes all its work.
for item in sequence:
Block of codes to execute
else:
Block of codes to execute if false
Else statement syntax in for loop
while condition:
Block of codes to execute
else:
Block of codes to execute if false
Else statement syntax in while loop
The break statement is like an emergency exit - it stops the loop immediately when you need it to.
:bulb: Use break when you find what you're looking for and don't need to continue.
python
for item in sequence: if condition: break codes to execute
Break statement syntax in for loop
python
while condition1: codes to execute if condition2: break codes to execute
Break statement syntax in while loop
3️⃣ Continue Statement
The continue statement skips the rest of the current loop and jumps to the next item. tip Use continue when you want to skip certain items but keep the loop running.
for item in sequence:
if condition:
continue
codes to execute
Continue statement syntax in for loop
while condition1:
codes to execute
if condition2:
continue
codes to execute
Continue statement syntax in while loop
Let's explore each concept with real examples you can try yourself!
Example One: Say Good Morning 3 Times
for i in range(3):
print("Good morning")
Expected output:
Good morning
Good morning
Good morning
Example 2: Count from 0 to 2
The range(3)
function gives us numbers 0, 1, and 2:
for i in range(3):
print(i)
Expected output:
0
1
2
Example 3: Print Multiples of 5
Let's create the multiplication table for 5:
x = 5
for i in range(5):
print(x)
x = x + 5
Expected output:
5
10
15
20
25
Example 4: Loop Through a List
For loops can go through each item in a list:
fruits = ["apple", "banana", "cherry"]
for i in fruits:
print(i)
Expected output:
apple
banana
cherry
Example 5: Loop Through Letters in a Word
You can even loop through each letter in a word:
string = "python"
for x in string:
print(x)
Expected output:
p
y
t
h
o
n
Example 6: Count from 1 to 5
With while loops, remember to set up your counter first:
x = 1
while x <= 5:
print(x)
x = x + 1
Expected output:
1
2
3
4
5
Example 7: Print All Multiples of 5 up to 50
x = 5
while x <= 50:
print(x)
x = x + 5
Expected output:
5
10
15
20
25
30
35
40
45
50
Example 8: Using Else with For Loop
fruits = ['apple', 'banana', 'cherry']
for i in fruits:
print(i)
else:
print("No items left.")
Expected output:
apple
banana
cherry
No items left.
Example 9: Using Else with While Loop
x = 5
while x <= 50:
print(x)
x = x + 5
else:
print("That's all for multiples of 5 up to 50")
Expected output:
5
10
15
20
25
30
35
40
45
50
That's all for multiples of 5 up to 50
Example 10: Stop a For Loop Early
This loop stops when it reaches 3:
for i in range(5):
if i == 3:
break
print(i)
Expected output:
0
1
2
Example 11: Stop a While Loop Early
x = 1
while x <= 5:
print(x)
if x == 3:
break
x = x + 1
Expected output:
1
2
3
Example 12: Skip Number 3 in For Loop
This loop skips printing 3 but continues with other numbers:
for i in range(5):
if i == 3:
continue
print(i)
Expected output:
0
1
2
4
Example 13: Skip Number 3 in While Loop
x = 0
while x < 5:
x = x + 1
if x == 3:
continue
print(x)
Expected output:
1
2
4
5
# For loop - repeat 5 times
for i in range(5):
print(i)
# While loop - count to 10
count = 1
while count <= 10:
print(count)
count = count + 1
Try using AI to help you create loops and practice what you've learned!
Beginner Level:
Intermediate Level:
Challenge Level: