Skip to main content
Practice

Loops: for and while

In programming, we often need to repeat actions — such as printing items, summing values, or checking conditions. Loops allow us to do this efficiently without rewriting the same code.

Python provides two main types of loops: for and while.


for Loops

A for loop is used when you want to go through each item in a sequence, such as a list, string, or range of numbers.

For Loop
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 in 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.

While Loop
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 it is true, the block runs.
  • After each loop, count increases by 1.
  • When count becomes 4, the condition is false and the loop stops.

When to Use Each

  • Use a for loop when you already know the collection of items you want to process.
  • Use a while loop when the number of repetitions depends on a condition that can change over time.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.