[Tutor] Print/Loop Question

Jack Trades jacktradespublic at gmail.com
Thu Mar 17 20:10:18 CET 2011

On Thu, Mar 17, 2011 at 1:19 PM, Jeff Goodwin <jeffbgoodwin at gmail.com>wrote:

> I'm trying to run the below program and get it to print out feedback as the
> loop goes. However, if you enter a number too high or too low, it skips the
> print statement under the if and elif clauses and asks the user to "Guess a
> number between 1-100" again. Any suggestions on how to get it to print the
> "too high" and "too low" responses?? Once the number is entered correctly it
> prints "Just Right" and exits correctly.
> number = 44
> while guess != number :
>     guess = int(raw_input("Guess a number between 1 - 100: "))
>     *if* guess > number :
>         *print* ("Too high")
>     *elif* guess < number :
>         *print* ("Too low")
>     *else*:
>         *print* ("Just right" )

Your solution is correct, except for one thing.

When you start the while loop 'guess' is not yet defined.  That's why it
gives you an error.  You need to define 'guess' before you start your while
loop, like so...

number = 44
guess = 0

while guess != number :
  guess = int(raw_input("Guess a number between 1 - 100: "))
  if guess > number :
    print ("Too high")
  elif guess < number :
    print ("Too low")
    print ("Just right" )

After that change it worked for me.  Did you get this error when you tried
your code?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'guess' is not defined

>From your question it sounds like I might be missing something though.  If
that didn't help, please provide more details.

Jack Trades
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110317/027e79ac/attachment.html>

More information about the Tutor mailing list