About These Examples
This page contains 20+ simple, practical examples demonstrating how to use the for loop in Python. Each example uses only a single for loop ā no nested loops ā making it perfect for beginners who are just getting started with loops.
š Note: These examples focus only on the for loop with numbers. Nested for loops will be covered in a separate topic.
ā” Performance Note: A simple for loop has O(n) time complexity ā it runs in linear time. For n items, it executes n times. This makes for loops very efficient for iterating over sequences.
š” Tip: Try to understand each example by reading the explanation first, then run the code yourself. The best way to learn programming is by doing!
1. Basic For Loop Examples 6 Examples
for i in range(1, 11):
print(i)
# Output: 1 2 3 4 5 6 7 8 9 10
The range(1, 11) function generates numbers starting from 1 and going up to, but not including, 11. So it gives us 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The for loop takes each number from this range, stores it in the variable i, and prints it. This is the most basic pattern you'll use with for loops ā iterating over a sequence of numbers.
š When to use this: Whenever you need to repeat an action a fixed number of times. For example, processing 10 items, generating a report for 10 days, or creating a countdown.
for i in range(2, 21, 2):
print(i)
# Output: 2 4 6 8 10 12 14 16 18 20
The range(2, 21, 2) function has three arguments: start (2), stop (21), and step (2). It starts at 2, goes up to but not including 21, and increments by 2 each time. This directly generates even numbers without checking each number individually. It's more efficient and cleaner than using an if statement inside the loop.
š When to use this: When you need to generate a sequence with a specific step size. For example, generating every 5th number, counting backwards, or creating a list of multiples.
for i in range(10, 0, -1):
print(i)
# Output: 10 9 8 7 6 5 4 3 2 1
The range(10, 0, -1) function starts at 10, stops before 0, and uses a step of -1 (going backwards). This creates a countdown sequence. The loop prints each number as it goes. This is how you do reverse iteration in Python ā it's very clean and easy to read.
š When to use this: When you need to process items in reverse order. For example, showing a countdown timer, processing data from newest to oldest, or reversing a sequence.
for i in range(1, 16, 2):
print(i, end=" ")
# Output: 1 3 5 7 9 11 13 15
The range(1, 16, 2) starts at 1, goes up to but not including 16, and steps by 2. This generates only odd numbers: 1, 3, 5, 7, 9, 11, 13, 15. The end=" " in the print function makes it print all numbers on the same line with a space between them.
š When to use this: When you need to generate odd numbers, every third number, or any arithmetic sequence. This pattern is used in mathematical computations and data processing.
for i in range(1, 6):
print(f"{i}² = {i**2}")
# Output:
# 1² = 1
# 2² = 4
# 3² = 9
# 4² = 16
# 5² = 25
The for loop iterates from 1 to 5. For each number i, we calculate its square using i**2 (the exponentiation operator). The f-string formatting makes it easy to create readable output. This demonstrates how you can perform calculations inside a loop and display the results in a nice format.
š When to use this: When you need to apply a calculation to each number in a sequence. For example, calculating powers, interest rates, or converting units.
for i in range(3, 31, 3):
print(i, end=" ")
# Output: 3 6 9 12 15 18 21 24 27 30
The range(3, 31, 3) starts at 3 and increments by 3, generating all multiples of 3 up to 30. This is useful for generating arithmetic sequences.
š When to use this: When you need to generate multiples of a number. For example, generating time intervals, price tiers, or any regular sequence.
2. Math & Number Operations 7 Examples
total = 0
for i in range(1, 51):
total += i
print(f"Sum: {total}")
# Output: Sum: 1275
We start with a variable total set to 0. The for loop goes through each number from 1 to 50, and in each iteration, we add the current number to total using total += i. After the loop finishes, total contains the sum of all numbers from 1 to 50. This is a classic accumulation pattern ā starting with zero and building up to the final result.
š When to use this: When you need to calculate totals, averages, or any running sum. For example, adding up sales figures, calculating scores, or computing statistical measures.
total = 0
for i in range(2, 101, 2):
total += i
print(f"Sum of evens: {total}")
# Output: Sum of evens: 2550
The range(2, 101, 2) generates all even numbers from 2 to 100. We add each even number to total just like in the previous example. This is more efficient than checking each number individually with an if statement because we're directly generating only the numbers we need.
š When to use this: When you need to calculate sums based on specific criteria. For example, summing only even numbers, odd numbers, or numbers that meet certain conditions.
n = 5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial: {factorial}")
# Output: Factorial: 120
Factorial (n!) means multiplying all numbers from 1 to n. For 5!, we multiply 1 Ć 2 Ć 3 Ć 4 Ć 5 = 120. We start factorial at 1 (the identity for multiplication), then multiply it by each number from 1 to n using the loop. The factorial *= i statement is shorthand for factorial = factorial * i. This is a classic example of accumulation with multiplication.
š When to use this: Factorials are used in probability, statistics, and combinatorics. For example, calculating permutations, combinations, or in algorithms for sorting.
n = 10
a, b = 0, 1
print("Fibonacci series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
# Output: 0 1 1 2 3 5 8 13 21 34
The Fibonacci series starts with 0 and 1. Each subsequent number is the sum of the two previous numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... We keep track of two numbers (a and b). In each iteration, we print a, then update a to b and b to a + b. The tuple unpacking a, b = b, a + b is a clean way to swap and update both values simultaneously.
š When to use this: Fibonacci numbers appear in nature (spirals, leaf arrangements), financial models, and computer algorithms (Euclidean algorithm, dynamic programming).
num = 5
for i in range(1, 11):
print(f"{num} Ć {i} = {num * i}")
# Output: 5 Ć 1 = 5 ... 5 Ć 10 = 50
The for loop runs from 1 to 10. For each value of i, we multiply the given number by i and print the result in a readable format. This generates a complete multiplication table for the number. The f-string formatting makes it easy to create a clean, organized output.
š When to use this: This pattern is used in many real-world applications, such as generating reports, creating invoices, calculating prices with tax, or any scenario where you need to apply a formula to a range of values.
num = 17
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is prime")
else:
print(f"{num} is not prime")
# Output: 17 is prime
A prime number is only divisible by 1 and itself. To check if num is prime, we test if it's divisible by any number from 2 to the square root of num. If we find a divisor, the number is not prime, and we use break to exit the loop early. Checking only up to the square root is much faster for large numbers because if num has a divisor greater than its square root, it must also have a divisor smaller than the square root.
š When to use this: Prime number checking is used in cryptography, hashing algorithms, and generating random numbers. This algorithm is a fundamental building block in many computer science applications.
total = 0
for i in range(1, 1001):
if i % 3 == 0 or i % 5 == 0:
total += i
print(f"Sum: {total}")
# Output: Sum: 234168
This is a classic problem (similar to Project Euler #1). We check each number and add it to the sum if it's divisible by 3 or 5. The OR operator ensures we don't double-count numbers divisible by both. This demonstrates how to combine conditional logic with accumulation in a for loop.
š When to use this: This pattern is used in data filtering, validation checks, and when you need to process only items that meet certain criteria.
3. Real-World Programs 6 Examples
n = int(input("How many numbers? "))
total = 0
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
total += num
average = total / n
print(f"Average: {average:.2f}")
This program first asks the user how many numbers they want to enter. Then it uses a for loop to collect each number, adding it to a running total. After all numbers are entered, it calculates the average by dividing the total by the count. The .2f formatting rounds the average to 2 decimal places for a clean output.
š When to use this: This is a common pattern in data entry applications, surveys, and statistical calculations. It shows how loops can be used to collect and process user input.
n = int(input("How many numbers? "))
numbers = []
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
numbers.append(num)
print(f"Maximum: {max(numbers)}")
print(f"Minimum: {min(numbers)}")
We collect all numbers in a list using a for loop. Then we use the built-in max() and min() functions to find the largest and smallest numbers. This is simpler than manually tracking maximum and minimum during the loop. However, if you want to avoid storing all numbers (for memory efficiency), you could track max and min manually as you go.
š When to use this: This is used in data analysis to find extremes in datasets. For example, finding the highest and lowest temperatures, scores, or sales figures.
principal = 10000
rate = 5
years = 10
amount = principal
for year in range(1, years + 1):
amount = amount * (1 + rate/100)
print(f"Year {year}: ā¹{amount:.2f}")
print(f"Total: ā¹{amount:.2f}")
Compound interest calculates interest on both the principal and the accumulated interest. The for loop computes the amount for each year by multiplying the previous amount by (1 + rate/100). This demonstrates exponential growth, where the amount increases by a percentage each year. The loop provides a year-by-year breakdown of how the investment grows.
š When to use this: This is used in banking, investing, and financial planning to calculate returns on investments, loan growth, and savings projections.
subjects = int(input("Enter number of subjects: "))
total_marks = 0
max_marks = 100
for i in range(subjects):
marks = float(input(f"Enter marks for subject {i+1}: "))
total_marks += marks
percentage = (total_marks / (subjects * max_marks)) * 100
print(f"Total: {total_marks}")
print(f"Percentage: {percentage:.2f}%")
This program calculates total marks and percentage for a student. The for loop collects marks for each subject, calculates the total, and then computes the percentage. The percentage is calculated as (total marks / maximum possible marks) Ć 100. This is a common academic calculation used in schools and universities.
š When to use this: This is used in educational systems for grading, progress reports, and academic analysis. The same pattern can be applied to any scoring system.
principal = 500000
rate = 8
months = 60
r = rate / 12 / 100
emi = principal * r * ((1 + r) ** months) / (((1 + r) ** months) - 1)
print(f"Monthly EMI: ā¹{emi:.2f}")
balance = principal
for month in range(1, months + 1):
interest = balance * r
principal_paid = emi - interest
balance -= principal_paid
if month % 6 == 0: # Print every 6 months
print(f"Month {month}: Balance ā¹{balance:.2f}")
This is a real-world financial calculation. The for loop generates an amortization schedule, showing how the loan balance decreases over time. Each month, we calculate the interest on the remaining balance, subtract it from the EMI to find the principal paid, and reduce the balance. The if month % 6 == 0 prints the balance every 6 months for a summary view.
š When to use this: This is used in banking and finance for loan management, mortgage calculations, and financial planning. It demonstrates how loops can model financial processes over time.
units = int(input("Enter units consumed: "))
if units <= 100:
bill = units * 5
elif units <= 200:
bill = 100 * 5 + (units - 100) * 7
else:
bill = 100 * 5 + 100 * 7 + (units - 200) * 10
print(f"Bill: ā¹{bill:.2f}")
This calculates electricity bill based on tiered pricing: first 100 units at ā¹5, next 100 at ā¹7, and above at ā¹10. While this uses if-elif-else rather than a loop, you could use a loop for more complex tier structures. This demonstrates how conditional logic can be combined with calculations to create real-world applications.
š When to use this: This is used in utility billing systems, tax calculations, and any scenario with tiered pricing or progressive rates.
4. Edge Cases & Advanced Concepts 4 Examples
break, continue, else.
for num in range(50, 101):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break # Exit inner loop early
if is_prime:
print(f"First prime found: {num}")
break # Exit outer loop
# Output: First prime found: 53
The break statement exits the loop immediately. Here, the inner break stops checking divisors when one is found. The outer break stops the search once the first prime is found. This makes the program much faster because it doesn't check unnecessary numbers. Without break, this would check every number up to 100. With break, it stops at 53.
š When to use this: Use break when you want to exit a loop early based on a condition. This is common in search algorithms, validation checks, and performance-critical code.
for i in range(1, 21):
if i % 3 == 0 or i % 5 == 0:
continue # Skip this iteration
print(i, end=" ")
# Output: 1 2 4 7 8 11 13 14 16 17 19
The continue statement skips the rest of the current iteration and moves to the next number. This is useful when you want to skip certain values without writing complex nested conditions. In this example, when a number is divisible by 3 or 5, we skip printing it and continue with the next number.
š When to use this: Use continue when you want to skip specific cases in a loop. This is common in data filtering, validation, and when handling exceptions.
num = 17
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(f"{num} is not prime")
break
else:
print(f"{num} is prime")
# Output: 17 is prime
The else clause in a for loop runs only if the loop completes without hitting a break. Here, if no divisor is found, the else block executes, confirming the number is prime. This is cleaner than using a flag variable. The for-else construct is a unique feature of Python that makes certain patterns more readable.
š When to use this: Use for-else when you need to check if a loop completed normally or was interrupted by a break. This is common in search algorithms and validation checks.
for i in range(5, 5):
print("This won't print")
else:
print("Loop ran zero times")
# Output: Loop ran zero times
When range(start, stop) has start equal to stop, it's an empty range. The loop body never executes. The else block still runs because the loop completed normally (just zero times). This is important to know when working with loops ā an empty range doesn't cause an error; it just skips the loop body.
š When to use this: This is useful when you want to handle the case where a range might be empty. For example, when processing a list that might be empty.
š For Loop vs While Loop
When working with numbers, both for and while loops can do similar tasks. But which one should you use? Here's a simple rule:
ā Use For Loop When:
- You know the number of iterations (e.g.,
range(10)) - You need to iterate over a sequence (list, range, string)
- You want cleaner, more readable code
- Example:
for i in range(1, 11): print(i)
ā Use While Loop When:
- You don't know the number of iterations in advance
- You need to loop until a condition changes (e.g., user input)
- You need more control over the loop condition
- Example:
while num != 0: num = int(input())
# For Loop - When you know the range
print("For Loop:")
for i in range(1, 6):
print(i, end=" ")
# Output: 1 2 3 4 5
# While Loop - When you need a condition
print("\nWhile Loop:")
num = 1
while num <= 5:
print(num, end=" ")
num += 1
# Output: 1 2 3 4 5
š” Quick Rule of Thumb: If you're counting or iterating over a known range, use for loop. If you're waiting for a condition to change (like user input), use while loop. This distinction is essential for writing clean, efficient code.
Try It Yourself!
Use the interactive editor below to test the examples or write your own code.
FOR LOOP EXAMPLES
========================================
1. NUMBERS 1 TO 10
1 2 3 4 5 6 7 8 9 10
2. SUM OF FIRST 10 NUMBERS
Sum: 55
3. EVEN NUMBERS UP TO 20
2 4 6 8 10 12 14 16 18 20
4. FACTORIAL OF 5
Factorial: 120
5. MULTIPLICATION TABLE OF 7
7 Ć 1 = 7
7 Ć 2 = 14
7 Ć 3 = 21
7 Ć 4 = 28
7 Ć 5 = 35
7 Ć 6 = 42
7 Ć 7 = 49
7 Ć 8 = 56
7 Ć 9 = 63
7 Ć 10 = 70
ā Write your solutions here!
š Related Tutorials
š For Loop
Learn the fundamentals of for loops
Learn āš For vs While
Learn the difference between for and while loops
Compare ā