For and While Loops

For and While Loops

For Loop

Iterating Over a Range

# Print 0 to 4
for i in range(5):
    print(i)

Print 1 to 5

for i in range(1, 6): print(i)

Print 0, 2, 4, 6, 8

for i in range(0, 10, 2): print(i)

Iterating Over a List

fruits = ["apple", "banana", "cherry"]

for fruit in fruits: print(fruit)

While Loop

count = 0

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

Loop Control

Break

for i in range(10):
    if i == 5:
        break
    print(i)  # Prints 0,1,2,3,4

Continue

for i in range(5):
    if i == 2:
        continue
    print(i)  # Prints 0,1,3,4 (skips 2)

Enumerate

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")

0: apple

1: banana

2: cherry

List Comprehension

# Create a list of squares
squares = [x2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Summary

  • For loops: iterate over sequences
  • While loops: repeat while condition is True
  • Break: exit the loop
  • Continue: skip to next iteration
  • List comprehension: create lists concisely

Next Lesson

In the next lesson, you'll learn about lists and tuples.

Quiz - Quiz - For and While Loops

1. What does range(5) generate?

2. What does break statement do?

3. What is list comprehension?

If/Else Statements