-2
import random

number = random.randint(0,10)
#print (number)

guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))

#print(guess)

while guess != number:
    if guess > number:
        print("That is too high!")
        guess = int(input())
    elif guess < number: 
        print("That is too low")
        guess = int(input())
    else: 
        print("Thats it! You win!")

I'm working out a few python coding examples and I am confused why my else statement isn't printing?

The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.

I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
confusedbeginner
  • 121
  • 1
  • 1
  • 9
  • 1
    `while guess != number:` it doesn't enter the while condition.(https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Lafexlos Jul 17 '19 at 06:33
  • ahhh got it. thanks! – confusedbeginner Jul 17 '19 at 06:36
  • I'm curious, what exactly goes wrong (why doesn't it enter while condition?) and how did you fix it? – Robvh Jul 17 '19 at 06:37
  • 1
    @Robvh For `else` to work, `number` should be equal to `guess` which doesn't satisfy `while` condition. About the fix, I am not sure about "the best way"(that's why I didn't add an answer) but you can put winning print out of while loop. – Lafexlos Jul 17 '19 at 06:40

1 Answers1

2

Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.

You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.

Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.

import random

number = random.randint(0, 10)

guess = None

while guess != number:
    guess = int(input())
    if guess > number:
        print("That is too high!")    
    elif guess < number: 
        print("That is too low")
    elif guess == number: 
        print("Thats it! You win!")
    else:
        print('that was not supposed to happen')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80