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
- The Collatz walk repeats until
nreaches 1. - The loop body updates the very condition it tests.
breakexits early the moment the target is found.
Keywords and builtins used here
breakelseifwhile
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.
Step 3 of 7 in Flow control, step 18 of 72 in Language basics.