⬅ Previous Topic
Python Conditional StatementsNext Topic ⮕
Introduction to Python Collections⬅ Previous Topic
Python Conditional StatementsNext Topic ⮕
Introduction to Python CollectionsLoops help us repeat actions in Python. Imagine telling the computer: "Do this again and again." That’s what loops are for!
Let’s say you want to print "Hi!" five times. Without a loop, you’d write:
print("Hi!")
print("Hi!")
print("Hi!")
print("Hi!")
print("Hi!")
That works… but what if you wanted to print it 100 times? That’s where loops save time.
for loops are great when you know how many times you want to repeat something.
for i in range(5):
print("Hi!")
Hi!
Hi!
Hi!
Hi!
Hi!
range(5)
means: go from 0 to 4 (5 numbers in total).i
takes values 0, 1, 2, 3, 4 — one at a time.print("Hi!")
runs 5 times, once for each value of i
.while loops repeat as long as a condition is true.
count = 1
while count <= 3:
print("Welcome!")
count = count + 1
Welcome!
Welcome!
Welcome!
count
starts at 1.count
.count
becomes 4 (because 4 is not ≤ 3).We can also use for
loops to go through a list of items.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
Each time, fruit
takes one value from the list and prints it.
break
stops the loop early.
for i in range(5):
if i == 3:
break
print(i)
0
1
2
i
becomes 3, the break
line runs and stops the loop.continue
skips the rest of the loop for that time only.
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
i
is 2, it skips print(i)
.Loops are a powerful way to repeat actions in Python. You learned:
break
to stop a loopcontinue
to skip one step in a loopPractice using loops in different ways — that’s the best way to understand how they work!
⬅ Previous Topic
Python Conditional StatementsNext Topic ⮕
Introduction to Python CollectionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.