Loops: for
and while
In programming, we often need to repeat actions — like printing items, summing values, or checking conditions. Loops let us do this efficiently without writing the same line multiple times.
Python offers two main types of loops: for
and while
.
for
Loops
A for
loop is used when you want to iterate over a sequence (like a list, string, or range of numbers).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
Explanation
fruits
is a list.- The variable
fruit
takes one value from the list on each loop. - The loop prints a sentence using that value.
- This repeats three times — once for each fruit.
while
Loops
A while
loop runs as long as a condition is true.
count = 1
while count <= 3:
print("Count is:", count)
count += 1
Explanation
- The loop starts with
count = 1
. - It checks the condition
count <= 3
. If true, it runs the block. - After each loop,
count
increases by 1. - When
count
becomes 4, the loop stops.
When to Use Each
- Use a
for
loop when you have a known set of items. - Use a
while
loop when you have a condition that might change over time.
Next, you’ll learn how to control loop flow using break
, continue
, and pass
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.