user3010791
user3010791

Reputation:

Confused with output from if condition within the while loop

I'm begging learn programming that is first code of python I wrote . well this is a guess game,if user type a number 5 wil print" you won " ,if it greater than 5 print " toohigh ", and if smaller than 5 print " too low ".

I wrote the code for that but when the user input number 5, it print " too low " and print " you won " that is not I want, when input number 5 which is supposed to output message "You won". I need explain for why the output of code say "too low" and say "You won" with user input 5 number??

print("Welcome")
guess = 0
while guess != 5:
    g = input("Guess a number: ")
    guess = int(g)
    if guess > 5:
        print("too high")
    else:
        print("too low")
print("You won")

The result is :

Guess a number: 4
too low
Guess a number: 6
too high
Guess a number: 5
**too low  // this isn't supposed to be, this is wrong
You won**

Upvotes: 2

Views: 77

Answers (2)

Stef D'haeseleer
Stef D'haeseleer

Reputation: 66

The problem is in the case where your guess = 5.

The first if is negative, so it moves on to the else and prints "too low".

Change

else:
        print("too low")

too

elif guess < 5:
       print("too low")

and this won't happen again. A good trick for beginners is to analyse the 'border cases', guess = 5 in this case and analyse what your program will do there.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201537

Your else needs to test that the value isn't 5.

else:

should be something like

elif guess < 5:

Because 5 isn't greater than 5.

Upvotes: 4

Related Questions