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 Loops are Important

Loops are important because they help programmers:

  • avoid repeated code
  • automate tasks
  • process large amounts of data
  • improve program efficiency
  • build real-world applications

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

How Loops Work

Step 1

Python checks the loop condition.


Step 2

If condition is True:

  • loop block executes


Step 3

Python again checks the condition.


Step 4

The process repeats until the condition becomes False.

Common Beginner Mistakes

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

Advantages of Loops

  • Reduces code repetition
  • Makes code shorter
  • Improves readability
  • Saves development time
  • Handles repetitive tasks easily

➤ Summary

  • Loop statements in Python are used to repeat tasks automatically.

    Python mainly provides two types of loops:

    • for loop
    • while loop

    Loops help programmers:

    • reduce repeated code
    • automate tasks
    • improve efficiency
    • build real-world applications

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