For Loop

Learn how to repeat code efficiently using for loops in Python.

Ali Berro

By Ali Berro

11 min read Section
From: Python Fundamentals: From Zero to Hero

For loops

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.

Basic Syntax

The syntax for a for loop is:

for variable in sequence:
# loop body here

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():

for i in range(5):
print(i)

This will output:

0
1
2
3
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:

i = 0
while i < 5:
print(i)
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.

Using range() with for loops

The range() function is commonly used with for loops to iterate over sequences of numbers. Let’s see various examples:

# 0 1 2 3 4
for i in range(5):
print(i, end=" ")
print()
# 2 3 4 5 6 7
for i in range(2, 8):
print(i, end=" ")
print()
# 1 3 5 7 9
for i in range(1, 10, 2):
print(i, end=" ")
print()
# 20 18 16 14 12 10 8 6 4 2
for i in range(20, 0, -2):
print(i, end=" ")

For loops vs While loops

When should a for loop be used instead of a while loop? Here are the key differences:

Use a for loop when:

  1. The number of iterations is known in advance - When a specific piece of code needs to be repeated a specific number of times:
# Print "Hello" 5 times
for i in range(5):
print("Hello")
  1. Iterating over a sequence - When each item in a sequence needs to be processed:
# Print numbers from 1 to 10
for i in range(1, 11):
print(i)
  1. Simpler, more readable code - for loops are often more concise and less error-prone:
# Sum numbers from 1 to 100
total = 0
for i in range(1, 101):
total += i
print(total)

Use while loops when:

  1. The number of iterations is unknown - When a condition needs to be checked before repeating code:
# Keep asking for input until user enters "quit"
response = ""
while response != "quit":
response = input("Enter a command (or 'quit' to exit): ")
  1. Complex condition logic - When the loop condition depends on multiple variables or complex logic:
# Keep reading numbers until sum exceeds 100
total = 0
while total <= 100:
num = int(input("Enter a number: "))
total += num
  1. Repeating forever until an event occurs - When using while True with break:
# Keep asking for password until correct
while True:
password = input("Enter password: ")
if password == "correct":
break

Note

Not all while loops can be easily converted to for loops, especially when the number of iterations is unknown or depends on runtime conditions.

Control flow with for loops

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:

for i in range(10):
if i % 2 != 0: # Skip odd numbers
continue
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:

i = 0
while i < 10:
if i % 2 != 0:
i += 1
continue
print(i, end=" ")
i += 1

The break statement exits the loop immediately, even if there are more items in the sequence:

for i in range(10):
if i == 5:
break
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):

for i in range(5):
print(i, end=" ")
else:
print("\nLoop completed normally")

If we use break, the else clause doesn’t execute:

n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print(n, "is not prime")
break
else:
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".

Nested for loops

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.

for i in range(4):
for j in range(4):
print("*", end="")
print()

This will output:

****
****
****
****

When using break or continue in nested loops, they only affect the innermost loop.

for i in range(3):
for j in range(i, i + 3):
if j % 3 == 0:
break # Only breaks out of inner loop
print("i = ", i, "j = ", j)

This will output:

i = 1 j = 1
i = 1 j = 2
i = 2 j = 2

Exercises

Solve these problems using for loops.

Exercise 1: Print numbers from 1 to 50

Write a program that prints all numbers from 1 to 50, each on a new line.

Print Numbers 1-50

Checks: 0 times
Answer:
for i in range(1, 51):
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

Checks: 0 times
Answer:
total = 0
for i in range(1, 101):
total += i
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:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

Multiplication Table

Checks: 0 times
Answer:
n = int(input())
for i in range(1, 11):
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:

*
**
***
****

Triangle Pattern

Checks: 0 times
Answer:
n = int(input())
for i in range(1, n + 1):
for j in range(i):
print('*', end='')
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:

*****
*****
*****

Rectangle Pattern

Checks: 0 times
Answer:
width = int(input())
height = int(input())
for i in range(height):
for j in range(width):
print('*', end='')
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=1205! = 1 \times 2 \times 3 \times 4 \times 5 = 120

Factorial

Checks: 0 times
Answer:
n = int(input())
factorial = 1
for i in range(1, n + 1):
factorial *= i
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:

****
***
**
*

Inverted Triangle

Checks: 0 times
Answer:
n = int(input())
for i in range(n, 0, -1):
for j in range(i):
print('*', end='')
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.

Example: If n = 4, the output should be:

1
12
123
1234

Number Pyramid

Checks: 0 times
Answer:
n = int(input())
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end='')
print()

Course Progress

Section 16 of 17

Back to Course