Lesson 6: Loops – For & While

1. Why Loops?

Loops let you repeat code — essential for processing lists, training models, or iterating over data in ML.

Two main types:

2. For Loop

Repeats for each item in a sequence.

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

Output:

apple
banana
cherry

With range():

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

Exercise 1

What does this code print?
for i in range(3, 6):
print(i)

3. While Loop

Repeats as long as condition is True.

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

Output: 0 1 2 3 4

Be careful: infinite loop if condition never becomes False!

Exercise 2

What is printed by this code?

i = 1
while i <= 3:
  print(i)
  i += 1
# Answer: 
  

Exercise 3

Which loops are infinite? (Select all that apply)
← Previous Lesson (5) Next Lesson (7) →