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 variable that 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 loop repeats 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

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

What is a for loop used for?

A for loop is used to repeat code multiple times.

Question 2

Which function is used with for loop?

range() is commonly used with for loops.

Question 3

What is the output?

for i in range(1, 4):
    print(i)

range(1,4) gives 1,2,3.

Question 4

What is the output?

total = 0
for i in range(1, 4):
    total += i

print(total)

1+2+3 = 6.

Question 5

What is the output?

for i in range(2, 6):
    print(i * 2)

range(2,6) → 2,3,4,5 → multiplied gives 4,6,8,10.

Congratulations!

You've successfully mastered the knowledge check for "for Loop."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic Introduction to Loops Next Topic while loop