Python Loops Tutorial

Loops are used to repeatedly execute a block of code. In Python, there are mainly two types of loops:

For Loops

The for loop in Python is used to iterate over a sequence (list, tuple, dictionary, set, or string) or other iterable objects.

for i in range(5):
    print(i)
        
0
1
2
3
4
        
Question: What will be the output if we change range(5) to range(2, 5)?
Answer: The output will start from 2 and end at 4 (not including 5).
for i in range(2, 5):
    print(i)
            
2
3
4
            

While Loops

The while loop in Python is used to execute a block of code as long as the condition is true.

i = 0
while i < 5:
    print(i)
    i += 1
        
0
1
2
3
4
        
Question: What will happen if we forget to increment the variable i inside the while loop?
Answer: If we forget to increment the variable i, the condition i < 5 will always be true, resulting in an infinite loop.

Nested Loops

Loops can be nested inside each other. This means you can have a loop inside another loop.

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")
        
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
        
Question: How many times will the inner loop execute?
Answer: The inner loop will execute 2 times for each iteration of the outer loop. Since the outer loop runs 3 times, the inner loop will run a total of 6 times.

Loop Control Statements

Python provides various loop control statements to change the loop's execution flow:

Break Example

for i in range(5):
    if i == 3:
        break
    print(i)
        
0
1
2
        

Continue Example

for i in range(5):
    if i == 3:
        continue
    print(i)
        
0
1
2
4
        

Pass Example

for i in range(5):
    if i == 3:
        pass
    print(i)
        
0
1
2
3
4
        

Questions and Exercises

Question: Write a Python program to print the first 10 Fibonacci numbers using a while loop.
Answer:
a, b = 0, 1
count = 0
while count < 10:
    print(a)
    a, b = b, a + b
    count += 1
            
0
1
1
2
3
5
8
13
21
34
            
Question: How can you use a for loop to iterate over a dictionary's keys and values?
Answer: You can use the items() method to get key-value pairs.
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(f"{key}: {value}")
            
a: 1
b: 2
c: 3