Imagine you want to print "Hello" 100 times. Writing print() 100 times would be a terrible idea! 😄
This is exactly why we use loops.
What is a Loop?
A loop is a programming structure that repeatedly executes a block of code until a certain condition is met or a sequence is completed.
For example, instead of:
print("Hello")
print("Hello")
print("Hello")
print("Hello")we can use a loop to repeat the same code.
Python mainly provides two types of loops:
Loop | Used When |
|---|---|
| You want to iterate over a sequence or a known range of values |
| You want to repeat code while a condition remains true |
for Loop
A for loop is commonly used to go through items one by one.
For example:
for i in range(5):
print("Hello")Output:
Hello
Hello
Hello
Hello
HelloHere, range(5) produces the values 0 through 4, so the loop runs five times.
You can also use a for loop with a list:
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)Output:
Apple
Banana
MangoThe loop takes each fruit from the list and runs the code for it.
while Loop
A while loop repeats code as long as a condition is true.
count = 1
while count <= 5:
print(count)
count += 1Output:
1
2
3
4
5Here, Python keeps running the loop while count <= 5.
Once count becomes 6, the condition becomes false and the loop stops.
Why Do We Need Loops?
Loops are useful whenever the same task needs to be performed repeatedly.
For example:
Printing numbers
Processing items in a list
Reading data
Repeating calculations
Processing files
Creating menus
Running a task until the user chooses to stop
Without loops, repetitive tasks would require a lot of duplicate code.
Loop Flow
A simple loop generally works like this:
Start
↓
Check condition / get next item
↓
Execute loop body
↓
Repeat
↓
Stop when finishedFor a while loop, it's especially important that the condition eventually becomes false.
For example:
count = 1
while count <= 3:
print(count)
count += 1The count += 1 changes the value each time, allowing the loop to eventually stop.
Infinite Loops
Be careful with while loops. If the condition never becomes false, the loop can continue forever.
For example:
count = 1
while count <= 5:
print(count)Here, count never changes, so count <= 5 remains true.
This creates an infinite loop.
break and continue
Python also provides statements that control how a loop behaves.
break
break immediately stops the loop.
for i in range(10):
if i == 5:
break
print(i)Output:
0
1
2
3
4continue
continue skips the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i)Output:
0
1
3
4We'll explore break and continue in more detail later.
A Simple Real-World Example
Suppose we want to print the names of students:
students = ["John", "Jason", "Alex"]
for student in students:
print(f"Welcome, {student}!")Output:
Welcome, John!
Welcome, Jason!
Welcome, Alex!Instead of writing three separate print() statements, the loop handles all the students for us.
for vs while
A simple way to remember the difference:
Use for when you're going through a collection or a known range:
for number in range(10):
print(number)Use while when repetition depends on a condition:
while balance > 0:
# do something
passLoops are one of the most important concepts in programming. Once you understand them, you can make your Python programs perform repetitive tasks automatically instead of writing the same code again and again.