for Loop
A for loop is used to repeat a block of code a fixed number of times.
It is helpful when we already know how many times we want to run the loop.
- The loop uses a
loop variablethat changes value in each step - It works with sequences like numbers, lists, or strings
- The
range()function is commonly used with for loops - It makes programs shorter and avoids repeated code
Explanation
- The loop starts from a number and goes step by step
- It stops when the limit is reached
- Each time, the loop variable changes its value
Real-Life Scenario
- Teacher calling roll numbers from 1 to 30
- Printing numbers from 1 to 10
- Showing marks of students one by one
Instead of writing print() many times, we use a loop
Syntax
for variable in range(start, end):
# code
Example 1
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
Example 2
total = 0
for i in range(1, 6):
total = total + i
print(total)
Output
15
Explanation of Example
range(1, 6)→ gives numbers 1 to 5- Loop adds all numbers → 1+2+3+4+5 = 15
Why for loop is Important
- Saves time by avoiding repeated code
- Helps in counting and iteration
- Used in real-world programs
- Builds logical thinking
Common Beginner Mistakes
- Forgetting that end value is not included
- Wrong indentation
- Using wrong range values
- Not understanding loop flow
➤ Key Points
for looprepeats code fixed number of times- Works with
range()function - Loop variable changes in each step
- Stops automatically when range ends
- Best for counting loops (1 to 10, etc.)
- Easy and safe to use
➤ Tips
- Use for loop when count is known
- range(start, end) → end value is not included
- Example:
range(1, 5)→ gives 1, 2, 3, 4 - Always use proper indentation
- Use meaningful variable names like i, num
- Good for printing numbers, lists, and tables