What's wrong with this code?

Tim Roberts timr at probo.com
Sat Jul 2 19:05:10 EDT 2005


"Nathan Pinno" <falcon3166 at hotmail.com> 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?
>
>  # Plays the guessing game higher or lower.
>  # Originally written by Josh Cogliati, improved first by Quique, then by
>Nathan Pinno.
>  print "Higher or Lower"
>  print
>  number = random.choice(range(100))
>  guess = 0
>  while guess != number:
>      guess = input("Guess a number: ")
>      if guess > number:
>          print "Too high"
>          guess = input("Guess a number: ")
>      elif guess < number:
>          print "Too low"
>          guess = input("Guess a number: ")
>  print "Just right"

There is a problem with this, caused by having to repeat the same code in
multiple places.  Sa that the number is 50.  You get to the first "input"
statment, and you enter 30.  It prints "Too low", and asks you to enter
another number.  You enter 40.  The "while" expression is true, so it will
loop again, and prompt you to enter ANOTHER number, without telling you
whether it was high or low.

Better to eliminate duplicated code:

import random
print "Higher or Lower"
print
number = random.choice(range(100))
while 1:
    guess = input("Guess a number: ")
    if guess == number:
        break
    elif guess > number:
        print "Too high"
    else:
        print "Too low"
print "Just right"
  
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list