The module below (magicword.py)
asks the user how many guesses he/she would like at the *magic word*.
This module is pretty skeletal, because it doesn't contain any ways to
handle exceptions and both the maximum number of guesses and the magic
word are enclosed in the module code itself, so that someone would have
to edit the code to change these values. This code should also be
improved in a number of other ways, but illustrates a few basic concepts
such as flow control, variable assignment and the use of comments.
# Find out how many guesses the user wants.
guessnum = input("How many guesses do you want? ")
# Set the maximum number of guesses to five.
if guessnum > 5:
guessnum = 5
print "We're using the maximum of five guesses."
# Ask for the magic word up to the maximum number of times.
i = 0
while i < guessnum:
i = i + 1
# Get the magic word.
magicword = raw_input("What's the magic word? ")
# Echo the user's guess back to them.
print "You guessed " + magicword + "."
# Test to see if the guess was correct.
if magicword == 'doh':
print "You guessed correctly."
break
else:
print "Guess number " + str(i) + " was incorrect."
# Keep the program running until the user ends the session.
raw_input("The magic word was 'doh'. Press return to exit the program. >")
The following is a session
with the *Python Shell* using the magicword.py module. In this case,
the program is started by issuing the command "import magicword", which
loads the module into memory.
>>> import magicwordBack to the MS_PIGgie Home Page
How many guesses do you want? 6
We're using the maximum of five guesses.
What's the magic word? spam
You guessed spam.
Guess number 1 was incorrect.
What's the magic word? rabbit
You guessed rabbit.
Guess number 2 was incorrect.
What's the magic word? Ni!
You guessed Ni!.
Guess number 3 was incorrect.
What's the magic word? lumberjack
You guessed lumberjack.
Guess number 4 was incorrect.
What's the magic word? Grail
You guessed Grail.
Guess number 5 was incorrect.
The magic word was 'doh'. Press return to exit the program. >