typestar

While loops in Python

Looping until a condition changes, not a fixed count.

n = 27
steps = 0
while n != 1:
    if n % 2 == 0:
        n //= 2
    else:
        n = 3 * n + 1
    steps += 1

guesses = [50, 25, 37, 42]
target = 42
while guesses:
    guess = guesses.pop(0)
    if guess == target:
        break

How it works

  1. The Collatz walk repeats until n reaches 1.
  2. The loop body updates the very condition it tests.
  3. break exits early the moment the target is found.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
188
Tokens
67
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 3 of 7 in Flow control, step 18 of 72 in Language basics.

← Previous Next →