2

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**

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

I know this solution But I want explation for why code doesn't consider while condition != 5 and else condition together to print only " You won "
The condition for the while loop (the one you are stating) is only evaluated after the whole loop to check if a new loop has to be started. So it will only be evaluated after the 'else' clause and not in between the 'if' and the 'else'. Does that clear it up for you?
Everything in the body of the while loop (all code with some space on the left) will run every time the while loop is called. So in the beginning of the while loop, the user can input a value for 'guess', the loop goes to the 'if', the loop goes to the 'else' and then checks the condition ( != 5). If guess is at that moment equal to 5, it will end the loop and go to the print statement (you won). If guess is not 5 (for example 4) the loop will start again and the user will be able to give a new input for 'guess'. This process is then repeated untill the condition is satisfied and the loop ends

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.