In the previous sections, we learned about while loops, which repeat code as long as a condition is true. However, when we know exactly how many times we want to repeat something, or when we want to iterate over a sequence of numbers, there’s a more elegant and readable way: the for loop.
The for loop in Python is designed to iterate over a sequence of items. While we haven’t learned about sequences like strings or lists yet, we can use for loops with the range() function we just learned about to iterate over sequences of numbers.
The variable takes on each value from the sequence one at a time, and the loop body executes once for each value. Let’s see this in action with range():
1
for i inrange(5):
2
print(i)
This will output:
1
0
2
1
3
2
4
3
5
4
The variable i takes on each value from range(5) (which is 0, 1, 2, 3, 4) one at a time, and we print it. Notice how we don’t need to manually increment i or check a condition—the for loop handles all of that for us automatically.
Let’s compare this to the equivalent while loop:
1
i =0
2
while i <5:
3
print(i)
4
i +=1
Both produce the same output, but the for loop is more concise and less error-prone. We don’t need to worry about forgetting to increment i or accidentally creating an infinite loop.
Just like while loops, for loops support continue, break, and else statements. The continue statement skips the remainder of the current iteration and moves to the next value in the sequence:
1
for i inrange(10):
2
if i %2!=0: # Skip odd numbers
3
continue
4
print(i, end=" ")
This will output: 0 2 4 6 8
Note
Notice how we don’t need to manually increment anything—the for loop automatically moves to the next value. This is simpler than the equivalent while loop:
1
i =0
2
while i <10:
3
if i %2!=0:
4
i +=1
5
continue
6
print(i, end=" ")
7
i +=1
The break statement exits the loop immediately, even if there are more items in the sequence:
1
for i inrange(10):
2
if i ==5:
3
break
4
print(i, end=" ")
This will output: 0 1 2 3 4
The else clause in a for loop executes only if the loop completes normally (without a break):
1
for i inrange(5):
2
print(i, end=" ")
3
else:
4
print("\nLoop completed normally")
If we use break, the else clause doesn’t execute:
1
n =int(input("Enter a number: "))
2
for i inrange(2, n):
3
if n % i ==0:
4
print(n, "is not prime")
5
break
6
else:
7
print(n, "is prime")
If we find a divisor, we break and print "not prime". If the loop completes without finding any divisor (no break occurred), the else clause executes and prints "prime".
Just like while loops, for loops can be nested. This is very useful for working with patterns, grids, or any situation where you need to iterate over multiple dimensions.
1
for i inrange(4):
2
for j inrange(4):
3
print("*", end="")
4
print()
This will output:
1
****
2
****
3
****
4
****
When using break or continue in nested loops, they only affect the innermost loop.
Write a program that prints all numbers from 1 to 50, each on a new line.
Print Numbers 1-50
Answer:
1
for i inrange(1, 51):
2
print(i)
Exercise 2: Sum of numbers from 1 to 100
Write a program that calculates and prints the sum of all numbers from 1 to 100.
Sum 1-100
Answer:
1
total =0
2
for i inrange(1, 101):
3
total += i
4
print(total)
Exercise 3: Print multiplication table
Write a program that reads a positive integer n from the user and prints the multiplication table for n from 1 to 10.
Example: If n = 5, the output should be:
1
5 x 1 = 5
2
5 x 2 = 10
3
5 x 3 = 15
4
...
5
5 x 10 = 50
Multiplication Table
Answer:
1
n =int(input())
2
for i inrange(1, 11):
3
print(n, 'x', i, '=', n * i)
Exercise 4: Print triangle pattern
Write a program that reads a positive integer n from the user and prints a triangle pattern with n rows. Each row should have a number of asterisks equal to its row number.
Example: If n = 4, the output should be:
1
*
2
**
3
***
4
****
Triangle Pattern
Answer:
1
n =int(input())
2
for i inrange(1, n +1):
3
for j inrange(i):
4
print('*', end='')
5
print()
Exercise 5: Print rectangle pattern
Write a program that reads two positive integers width and height from the user and prints a rectangle pattern with the specified dimensions.
Example: If width = 5 and height = 3, the output should be:
1
*****
2
*****
3
*****
Rectangle Pattern
Answer:
1
width =int(input())
2
height =int(input())
3
for i inrange(height):
4
for j inrange(width):
5
print('*', end='')
6
print()
Exercise 6: Factorial using for loop
Write a program that reads a positive integer n and calculates and prints its factorial using a for loop. Factorial of n (denoted as n!) is the product of all positive integers from 1 to n.
Example: 5!=1×2×3×4×5=120
Factorial
Answer:
1
n =int(input())
2
factorial =1
3
for i inrange(1, n +1):
4
factorial *= i
5
print(factorial)
Exercise 7: Print inverted triangle
Write a program that reads a positive integer n from the user and prints an inverted triangle pattern with n rows.
Example: If n = 4, the output should be:
1
****
2
***
3
**
4
*
Inverted Triangle
Answer:
1
n =int(input())
2
for i inrange(n, 0, -1):
3
for j inrange(i):
4
print('*', end='')
5
print()
Exercise 8: Print number pyramid
Write a program that reads a positive integer n from the user and prints a number pyramid with n rows.