Introduction to Loops

Loops in Python are used to repeat a block of code multiple times.

Instead of writing the same code again and again, we use loops to make programs short, simple, and efficient.

Real-Life Example

Loops are like daily activities:

  • Brushing teeth every day
  • Counting numbers
  • Repeating homework practice

Why Use Loops?

  • Saves time and effort
  • Reduces repeated code
  • Makes programs efficient
  • Helps in solving problems easily

Types of Loops in Python

1. for Loop

The for loop is used to repeat code a fixed number of times.

 It is commonly used when we know how many times we want to repeat something.

Example

for i in range(5):
    print(i)

Output

0
1
2
3
4

The loop runs 5 times

2. while Loop

The while loop is used to repeat code until a condition becomes False

 It is used when we don’t know how many times the loop will run.

Example

x = 0

while x < 5:
    print(x)
    x += 1

Output

0
1
2
3
4

Loop runs until x < 5 becomes False

Difference Between for and while

for loop while loop
Fixed number of times Runs based on condition
Easy to use Needs condition control
Used with range() Used with condition

Common Beginner Mistakes

  •  Infinite loop in while
  •  Wrong indentation
  •  Forgetting to update variable
  • Wrong range values

➤ Key Points

  • Loops repeat code multiple times
  • for loop → fixed repetitions
  • while loop → condition-based
  • Helps reduce code length
  • Improves logic building

➤ Tips

  • Use for loop when count is known
  • Use while loop when condition is needed
  • Avoid infinite loops
  • Practice with small examples

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

What are loops used for?

Loops are used to repeat code multiple times.

Question 2

Which loop runs a fixed number of times?

for loop runs a fixed number of times.

Question 3

What is the output?

for i in range(3):
    print(i)

range(3) starts from 0 → prints 0,1,2.

Question 4

When does a while loop stop?

while loop stops when condition becomes False.

Question 5

What is the output?

x = 1

while x < 4:
    print(x)
    x += 1

Loop runs until x = 3, then stops.

Congratulations!

You've successfully mastered the knowledge check for "Introduction to Loops."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic Nested if Statements Next Topic for Loop