Python 24-Day Course - Day 6: Loops

Day 6: Loops

for Loop

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

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

for i in range(1, 10, 2):
    print(i, end=" ")  # 1 3 5 7 9

enumerate and zip

names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names):
    print(f"{i}: {name}")

scores = [90, 85, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score} points")

while Loop

count = 0
while count < 5:
    print(count, end=" ")
    count += 1
# 0 1 2 3 4

break, continue, else

# break: stop the loop
for num in range(10):
    if num == 5:
        break
    print(num, end=" ")  # 0 1 2 3 4

# continue: skip the current iteration
for num in range(10):
    if num % 2 == 0:
        continue
    print(num, end=" ")  # 1 3 5 7 9

# for-else: else runs if loop completes without break
for n in range(2, 10):
    for d in range(2, n):
        if n % d == 0:
            break
    else:
        print(f"{n} is a prime number")

Today’s Exercises

  1. Write a program that prints multiplication tables from 2 to 9.
  2. Print the first 20 terms of the Fibonacci sequence.
  3. Keep accepting numbers from the user until they type “quit”, then print the total sum.

Was this article helpful?