while loops

motivation

A while loop should be used anytime we want our programs to loop, but don't know ahead of time how many iterations are needed. Examples include:

We've talked about the tic-tac-toe game in class. It's possible the game could end after 5 moves (three from "x", two from "o", and "x" wins). But it could also go to as many as 9 moves. In pseudo-code, this would be:

while game is not over:
  # player takes a turn
  # update/display the new board

syntax

The syntax is exactly the same as the if statement:

while some condition is True:
  # do this indented code block
  # could be 1 or more lines
  # then go back to the top and recheck the condition

However, as long as the condition is True, it will keep looping and repeating the code block.

The if statement will do the code block once if the condition is True. The while loop will recheck the condition after the code block, and repeat it if the condition is still True.

examples

Here's what I call the while loop game:

level = 4
while level > 0:
  print("At level: %d" % (level))
  char = raw_input("char (u/d): " )
  if char == "u":
    level += 1
  elif char == "d":
    level -= 1

It probably won't outsell Candy Crush, but it's a fine example of a while loop. If the user enters u, we move up a level. If the user enters d, we move down a level. And we keep going as long as level > 0. Here's an example of the running program:

At level: 4
char (u/d): d
At level: 3
char (u/d): d
At level: 2
char (u/d): u
At level: 3
char (u/d): d
At level: 2
char (u/d): d
At level: 1
char (u/d): d

Technically, this game could go on for a long time, if the user enters u a lot.

challenge

We can use the choice() function from the random library to simulate flipping a coin:

from random import *

flip = choice(["Heads", "Tails"])

Write a program that keeps flipping a coin until we've flipped 100 'Heads'. Have your program output the results as it does each coinflip:

Got Tails.....number of heads =   0
Got Heads.....number of heads =   1
Got Tails.....number of heads =   1
Got Tails.....number of heads =   1
Got Tails.....number of heads =   1
Got Tails.....number of heads =   1
Got Tails.....number of heads =   1
Got Tails.....number of heads =   1
Got Heads.....number of heads =   2
Got Tails.....number of heads =   2
Got Heads.....number of heads =   3
...
...
Got Tails.....number of heads =  98
Got Heads.....number of heads =  99
Got Heads.....number of heads = 100

CS21 Topics