while Loops

Looping Constructs

Program flow is rarely linear

  • Branches ⟶ if/elif/else

  • Repeated execution ⟶ loops

  • Python has only two looping constructs

  • while

    • Handcrafted loop condition

    • ⟶ very verbose coding

    • Most general looping construct

  • for

    • iteration over something sequencish

    • Iteration … generators … yield … outright genius!

    • ⟶ later

while Loops

General form of a ``while`` loop

while condition:
    statements
  • condition is a boolean expression

  • statements is an indented block of … well

    … statements

  • Block is executed while condition holds

Example: sum of numbers 1..100

sum = 0
i = 1
while i <= 100:
    sum += i
    i += 1

Note

Pythonicity

This example is rather contrived. One would rather use the built-in sum() function (documentation here), combined with the range() function (documentation here) to do the same.

sum(range(1,101))

break and continue

Fine grained loop control

  • break ends the loop

  • continue ends the current loop and continues with the next - evaluating the condition

For example: roll dice, until it shows six eyes …

import random

while True:
    eyes = random.randrange(1,7)
    if eyes == 6:
        print('hooray!')
        break

Esoteric Feature: while/else

Loops can have an “else” clause

  • Entered when loop terminates naturally

  • not terminated by a break

  • Natural while loop termination: loop condition evaluates to False

For example: roll dice six times. Win when it shows six eyes at least once, lose when not.

Non-pythonic (using a flag)

Pythonic (else on while)

import random

seen_sixeyes = False
n_tries = 0
while n_tries < 6:
    n_tries += 1
    eyes = random.randrange(1,7)
    if eyes == 6:
        seen_sixeyes = True
        break

if seen_sixeyes:
    print('hooray!')
else:
    print('lose!')
import random

n_tries = 0
while n_tries < 6:
    n_tries += 1
    eyes = random.randrange(1,7)
    if eyes == 6:
        print('hooray!')
        break
else:
    print('lose!')