Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Loops?For Loops BasicsWhile Loops BasicsLoop ControlIterating ListsLoop PatternsNested LoopsDebugging LoopsBest Practices
Python/Loops/For Loops Basics

📊 For Loops Basics — Master the Most Common Loop

For loops are perfect when you know exactly how many times you need to repeat something.


🎯 For Loop Syntax

for variable in sequence:
    # code to repeat
    print(variable)

Three essential parts:

1. `for` — keyword

2. `variable` — takes each value from the sequence

3. `sequence` — the range or list to iterate over


💡 The range() Function

The `range()` function generates a sequence of numbers. It's the most common way to loop a specific number of times.

# range(stop) - counts from 0 to stop-1
for i in range(5):
    print(i)  # Prints: 0, 1, 2, 3, 4

# range(start, stop) - counts from start to stop-1
for i in range(2, 5):
    print(i)  # Prints: 2, 3, 4

# range(start, stop, step) - counts with a step
for i in range(0, 10, 2):
    print(i)  # Prints: 0, 2, 4, 6, 8

🎨 Practical Examples

Example 1: Simple counting

# Count from 1 to 5
for number in range(1, 6):
    print(f"Number: {number}")

Example 2: Multiplication table

# Print the 5 times table
for i in range(1, 11):
    result = 5 * i
    print(f"5 × {i} = {result}")

Example 3: Accumulating values

# Sum numbers from 1 to 100
total = 0
for number in range(1, 101):
    total = total + number
print(f"Sum: {total}")  # 5050

🔄 Iterating Through Lists

For loops work perfectly with lists:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"I like {fruit}")

📊 For vs Range

SituationUseExample
Count 1 to 10`range(1, 11)``for i in range(1, 11):`
Loop 5 times`range(5)``for i in range(5):`
Process listList directly`for item in my_list:`
Every 2nd number`range(0, 10, 2)``for i in range(0, 10, 2):`

🔑 Key Takeaways

ConceptRemember
range(n)Starts at 0, goes up to n-1
Syntax`for variable in sequence:`
IndentationCode inside loop must be indented
VariableCreates new variable each iteration

🔗 What's Next?

Explore While Loops Basics for condition-based repetition!


Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn