[Tutor] guess my number game (reversed)

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jun 1 13:12:02 EDT 2018


On 01/06/18 14:00, chiara pascucci wrote:

> the user's input. The programme works fine if the it guesses the number
> right on its first try, but when the users inputs "too low" or "too high"
> an infinite loop is returned. I thinkI have done something wrong in my
> while loop and that my sentry variable is somehow wrong

Nope, it's simpler than that.

You only ask the user for input once, outside the loop.
Move the input() statement inside the loop before the if
statements and all should be well. (You will also need to
initialise answer to some value - an empty string
say - before entering the while loop.)

> print("think of a number from 1 to 100")
> print("I will try and guess it!")
> 
> import random
> 
> number = random.randint(1,100)
> print(number)
> 
> answer = input("is this right, too high, or too low?")
> 
> while answer != "right":
>     if answer == "too high":
>         number2 = random.randint(1,number)
>         print(number2)
>     elif answer == "too low":
>         number3 = random.randint(number,100)
>         print(number3)
> 
> print("I finally guessed your number. Thank you for playing")

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list