§ 2.5.2section 12 of 18·~5 min
for and while loops
A for loop runs once for each item in a collection. It's the workhorse of row-by-row processing.
amounts = [499, 1299, 250]
total = 0
for a in amounts:
total += a
print(total)
for i, a in enumerate(amounts):
print(i, a)
OUTPUT
2048
0 499
1 1299
2 250range(n) gives the numbers 0 to n-1. while repeats as long as a condition stays True, which you'll mostly see in retry loops. break exits a loop early and continue skips to the next item.
attempts = 0
while attempts < 3:
attempts += 1
print("connecting, attempt", attempts)
OUTPUT
connecting, attempt 1
connecting, attempt 2
connecting, attempt 3