For loops and range in Python
Counting loops: range's start, stop, and step in action.
total = 0
for n in range(1, 11):
total += n
evens = []
for n in range(0, 20, 2):
evens.append(n)
for i, letter in enumerate("abc"):
print(i, letter)
countdown = []
for n in range(5, 0, -1):
countdown.append(n)
How it works
range(1, 11)walks 1 through 10, accumulating a sum.- A step of 2 visits only the evens.
enumeratepairs each item with its index.- A negative step counts down.
Keywords and builtins used here
enumerateforprintrange
The run, in numbers
- Lines
- 14
- Characters to type
- 212
- Tokens
- 80
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 56 seconds.
Step 2 of 7 in Flow control, step 17 of 72 in Language basics.