Lesson 8 – Loops (while & for)

Loops allow your program to repeat actions automatically. Instead of writing the same line many times, you can use a loop to perform the task efficiently. Python provides two main types of loops: while loops and for loops.

What Is a While Loop?

A while loop repeats as long as its condition is true. You must update the variable inside the loop; otherwise, it will run forever.

Example 1: Counting from 1 to 5

i = 1

while i <= 5:
    print(i)
    i += 1
        

Output:

1
2
3
4
5
        

Explanation:

The loop continues because i <= 5 is true. Each time the loop runs, i increases by 1.

What Is a For Loop?

A for loop repeats a block of code a specific number of times. It is commonly used with range() or with lists.

Example 2: Counting using a for loop

for i in range(1, 6):
    print(i)
        

Output:

1
2
3
4
5
        

Explanation:

range(1, 6) generates numbers 1 to 5. The loop runs once for each value.

Looping Through a List

You can use a for loop to process each item inside a list.

Example 3: Printing fruit names

fruits = ["apple", "banana", "mango"]

for item in fruits:
    print(item)
        

Output:

apple
banana
mango
        

Quiz: Test Your Understanding

1. Which loop runs while a condition is true?

for
repeat
while
loop
Correct answer: while

2. What does range(1, 4) produce?

1, 2, 3, 4
1, 2, 3
0, 1, 2, 3
2, 3, 4
Correct answer: 1, 2, 3

3. Which loop is best for going through list items?

for
while
repeat
check
Correct answer: for

4. What will this code print?

for i in range(3):
    print("Hi")
            
Hi
Hi Hi
Hi Hi Hi
Nothing
Correct answer: Hi Hi Hi

5. What must change inside a while loop to avoid an infinite loop?

The print statement
The loop variable
The file name
Nothing needs to change
Correct answer: The loop variable
Back to Top