Python For Loop Tutorial for Beginners: 10 Real Examples

The for loop is one of the most useful tools in Python. It lets you repeat actions, process lists, read files, and automate boring tasks. Instead of writing the same code ten times, you write it once inside a loop.

In this tutorial, you will learn Python for loops through 10 practical examples that go from simple counting all the way to processing real-world data.

How a For Loop Works

A for loop iterates over a sequence (like a list, string, or range) and executes a block of code for each item.

# Basic syntax
for item in sequence:
    # do something with item
    pass

The loop variable (item) takes on each value in the sequence, one at a time. When the sequence is exhausted, the loop ends.

Example 1: Counting Numbers

The simplest use of a for loop — counting from 1 to 10.

for number in range(1, 11):
    print(number)

Output:

1
2
3
4
5
6
7
8
9
10

The range(1, 11) function generates numbers from 1 up to (but not including) 11.

Example 2: Looping Through a List

Process each item in a list without writing repetitive code.

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

for fruit in fruits:
    print(f"I like {fruit}")

Output:

I like apple
I like banana
I like cherry
I like mango
I like grape

Example 3: Summing Numbers in a List

Calculate the total of a list of numbers.

expenses = [45.50, 120.00, 33.75, 89.99, 15.00]
total = 0

for amount in expenses:
    total += amount

print(f"Total expenses: ${total:.2f}")

Output:

Total expenses: $304.24

Example 4: Using enumerate() for Index and Value

When you need both the position and the value, use enumerate().

languages = ["Python", "JavaScript", "Go", "Rust", "Java"]

for index, language in enumerate(languages, start=1):
    print(f"{index}. {language}")

Output:

1. Python
2. JavaScript
3. Go
4. Rust
5. Java

Example 5: Looping Through a String

Strings are sequences too. You can loop through each character.

word = "Python"
vowels = "aeiouAEIOU"
vowel_count = 0

for char in word:
    if char in vowels:
        vowel_count += 1

print(f"'{word}' has {vowel_count} vowel(s)")

Output:

'Python' has 1 vowel(s)

Example 6: Nested For Loops

A loop inside a loop. Useful for grids, tables, and combinations.

# Multiplication table for 1-5
for i in range(1, 6):
    row = ""
    for j in range(1, 6):
        row += f"{i*j:4d}"
    print(row)

Output:

   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Example 7: Filtering Items with a Condition

Combine a for loop with an if statement to select specific items.

scores = [82, 45, 91, 67, 73, 88, 55, 96, 42, 78]
passing = []

for score in scores:
    if score >= 70:
        passing.append(score)

print(f"Passing scores: {passing}")
print(f"Pass rate: {len(passing)}/{len(scores)}")

Output:

Passing scores: [82, 91, 73, 88, 96, 78]
Pass rate: 6/10

Example 8: Looping Through a Dictionary

Dictionaries let you loop through keys, values, or both.

student_grades = {
    "Alice": 92,
    "Bob": 78,
    "Charlie": 85,
    "Diana": 96,
    "Eve": 71
}

print("Honor Roll (90+):")
for name, grade in student_grades.items():
    if grade >= 90:
        print(f"  {name}: {grade}")

Output:

Honor Roll (90+):
  Alice: 92
  Diana: 96

Example 9: Reading a File Line by Line

For loops are perfect for processing text files without loading everything into memory.

# First, create a sample file
with open("sample.txt", "w") as f:
    f.write("Python is fun\n")
    f.write("Loops save time\n")
    f.write("Practice makes perfect\n")

# Now read it line by line
line_number = 0
with open("sample.txt", "r") as f:
    for line in f:
        line_number += 1
        print(f"Line {line_number}: {line.strip()}")

Output:

Line 1: Python is fun
Line 2: Loops save time
Line 3: Practice makes perfect

Example 10: List Comprehension (For Loop in One Line)

Python offers a compact syntax for creating lists from loops.

# Traditional for loop
squares = []
for n in range(1, 11):
    squares.append(n ** 2)

# Same thing as a list comprehension
squares_v2 = [n ** 2 for n in range(1, 11)]

print(f"Squares: {squares_v2}")

# With a condition: only even squares
even_squares = [n ** 2 for n in range(1, 11) if n % 2 == 0]
print(f"Even squares: {even_squares}")

Output:

Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Even squares: [4, 16, 36, 64, 100]

Controlling Loop Flow: break and continue

Two keywords let you control what happens inside a loop.

break — Stop the Loop Early

# Find the first number divisible by 7
for num in range(1, 100):
    if num % 7 == 0:
        print(f"First number divisible by 7: {num}")
        break

Output:

First number divisible by 7: 7

continue — Skip to the Next Iteration

# Print only odd numbers
for num in range(1, 11):
    if num % 2 == 0:
        continue
    print(num, end=" ")
print()

Output:

1 3 5 7 9

Common Mistakes to Avoid

Here are errors beginners frequently make with for loops:

  • Modifying a list while looping through it (causes skipped items or errors)
  • Forgetting the colon at the end of the for line
  • Wrong indentation inside the loop body
  • Using range(10) expecting it to include 10 (it goes 0-9)
# Wrong: range(5) gives 0,1,2,3,4 not 1,2,3,4,5
for i in range(5):
    print(i, end=" ")
print()

# Right: range(1, 6) gives 1,2,3,4,5
for i in range(1, 6):
    print(i, end=" ")
print()

Output:

0 1 2 3 4
1 2 3 4 5

FAQ

What is the difference between for and while loops in Python?

A for loop iterates over a known sequence (list, range, string). A while loop continues as long as a condition is True. Use for loops when you know how many iterations you need; use while loops when you do not know in advance.

Can I use a for loop with a dictionary?

Yes. Use .items() to get both keys and values, .keys() for just keys, or .values() for just values. By default, looping over a dictionary iterates over its keys.

What does range() do in a for loop?

The range() function generates a sequence of numbers. range(5) gives 0 through 4. range(1, 10) gives 1 through 9. range(0, 20, 2) gives even numbers from 0 to 18. It does not include the end value.

How do I loop through two lists at the same time?

Use the zip() function: for a, b in zip(list1, list2). This pairs up elements from both lists. If the lists have different lengths, zip stops at the shorter one.

Is a list comprehension faster than a regular for loop?

In most cases, yes — list comprehensions are slightly faster because they are optimized internally by Python. However, for beginners, readability matters more than speed. Use whichever you find clearer.

Leave a Comment

Scroll to Top