very newbie question

Peter Anderson peter.anderson at internode.on.net
Fri Aug 8 07:58:57 CEST 2008


Try this:

# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100."
print "Try to guess it in as few attempts as possible.\n"

# set the initial values
the_number = random.randrange(100) + 1
tries = 0

def ask_number():
guess = int(raw_input("Take a guess: "))
tries = 1

while (guess != the_number):
if (guess > the_number):
print "Lower..."
else:
print "Higher..."
tries += 1
guess = int(raw_input("Take a guess: "))
tries += 1

ask_number()

print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"

raw_input("\n\nPress the enter key to exit.")

The variables "the_number" and "tries" were not available outside the 
"ask_number()" module.

Alternatively drop the def function and lump it all into a simple script.
-- 
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things—Niccolo Machiavelli, /The Prince/, 
ch. 6



More information about the Python-list mailing list