Menu

Loops

Introduction

Loops let you repeat actions. Python has two main loop types: for loops and while loops. Python's for loop is particularly elegant — it iterates directly over items rather than using index counters.

For loops

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Using range()
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 2): # 2, 4, 6, 8
    print(i)

# enumerate() for index + value
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# zip() to iterate over multiple sequences
names = ["Alice", "Bob"]
scores = [95, 87]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

While loops

count = 0
while count < 5:
    print(count)
    count += 1

# break and continue
for i in range(10):
    if i == 3:
        continue  # skip 3
    if i == 7:
        break     # stop at 7
    print(i)  # prints 0, 1, 2, 4, 5, 6

Assignment

  1. Read about for statements in the Python docs.
  2. Write a program that prints all prime numbers up to 100 using loops.
  3. Practice using enumerate() and zip().

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!