Loops: Do It Again!
Loops: Do It Again! π
What if you need to do something many times β like adding up 100 numbers, or checking every item in a list? You don't write the same line 100 times. You use a loop!
for loops
A for loop repeats code once for every item in something, like a range of numbers or a list:
for i in range(5):
print(i)
# prints 0, 1, 2, 3, 4
range(5) means "the numbers 0 up to (but not including) 5." You can also loop directly over a list:
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
A super common pattern is building up a total inside a loop:
total = 0
for n in [1, 2, 3]:
total = total + n
print(total) # 6
while loops
A while loop keeps repeating as long as a condition stays True:
count = 0
while count < 3:
print(count)
count = count + 1
Be careful with while loops β if the condition never becomes False, your loop will run forever! Always make sure something inside the loop is working toward ending it.
Let's practice both kinds!