typestar

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

  1. range(1, 11) walks 1 through 10, accumulating a sum.
  2. A step of 2 visits only the evens.
  3. enumerate pairs each item with its index.
  4. A negative step counts down.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 7 in Flow control, step 17 of 72 in Language basics.

← Previous Next →