Computers are great at doing the same thing many times. A loop lets you repeat a block of code without writing it over and over.
The for loop
friends = ['Ana', 'Ben', 'Cy']
for name in friends:
print('Hi, ' + name)The
for loop visits every item in the list. On each pass, it puts that item into the variable between for and in. Here, name holds 'Ana', then 'Ben', then 'Cy'. The indented line runs once for each friend.range()
for i in range(5):
print(i)range(n) gives you the numbers from 0 up to (but not including) n. If you pass two arguments, like range(2, 6), it starts at 2 and stops before 6. This is handy when you need a specific count or range.Looping over strings
word = 'cat'
for letter in word:
print(letter)A string is just a sequence of characters. You can loop over it exactly like you would a list.
Building totals
total = 0
for n in [1, 2, 3]:
total = total + n
print(total)Start a variable at zero. Inside the loop, add each number to it. By the end,
total holds the sum of everything you added.The while loop
count = 3
while count > 0:
print(count)
count = count - 1
print('Liftoff!')while repeats as long as its condition is true. You must change something inside the loop to make it false eventually, or your program will run forever and freeze.break and continue
for i in range(10):
if i == 5:
break
print(i)break exits the loop immediately. continue skips the rest of this pass and jumps to the next one. Use them carefully; too many can make code hard to follow.