What's wrong with this code?
John Machin
sjmachin at lexicon.net
Sat Jul 2 19:50:32 EDT 2005
Nathan Pinno wrote:
> Hi all,
>
> What's wrong with the following code? It says there is name error, that
> random is not defined. How do I fix it?
Others have already answered that question. This posting is a
pre-emptive strike to head off the next half-a-dozen questions.
>
> # Plays the guessing game higher or lower.
> # Originally written by Josh Cogliati, improved first by Quique, then by
> Nathan Pinno.
Some of us are interested in the process by which great pieces of code
arise, how they are meticulously honed and polished, which craftpersons
contributed what ... is it possible for you to publish the earlier versions?
> print "Higher or Lower"
> print
> number = random.choice(range(100))
"number" will refer to one of: 0, 1, ......, 98, 99
> guess = 0
so you'll get a strange result by using zero here; try -1 instead
> while guess != number:
> guess = input("Guess a number: ")
"guess" will refer to a string e.g. "42" which will *not* compare equal
to the integer 42. Also you should use raw_input, not input.
so do this:
guess = int(raw_input("Guess a number: "))
> if guess > number:
> print "Too high"
> guess = input("Guess a number: ")
This will cause your program to ask TWICE per trip around the loop. Lose it.
> elif guess < number:
> print "Too low"
> guess = input("Guess a number: ")
... and again.
> print "Just right"
>
General advice:
1. Look on the Python web site (http://www.python.org) for an
introduction to Python for non-programmers.
2. Join the Python tutor list.
3. In this news group, read a little more than the threads that you have
started; this guessing game was discussed in a thread started by
somebody calling themselves ChuckDubya on 29 June!! Homework??
HTH,
John
More information about the Python-list
mailing list