While Loops
In class today, we worked through the use of while loops for creating
a game that lets a user guess a number from 1 to 100, with the
computer providing "Higher"/"Lower" hints along the way.
We developed several variants of the program, with source code as follows:
-
guessA.py
Our initial version. It is structured with a fake first guess
to get into the main while loop, with the real user input chosen
immediately within the loop body.
-
guessB.py
A revision of our first version where we ask for the first guess
before the loop, and then ask for each subsequnt guess at the
end of each iteration of the body. We also demonstrate that
the congratulatory message could be done after the loop body (we
could have made such a change in the first version as well).
-
guessC.py
This uses the basic structure from "guessB" version, but this
time wraps that logic in an outer while loop that manages the
dialog for allowing the user to play multiple rounds of the game
within a single execution of the software.
-
guessD.py
Identical logic to "guessC" except we gave a previous of the use
of user-defined functions to better organize source code.
Instead of having the inner process coded directly nested in the
outer loop, we have defined a playRound() function and
then make a call to that function from within the broader loop.
Michael Goldwasser
Last modified: Wednesday, 16 February 2011