Reputation: 3
in this little number guessing game, I have made in python, I intend on giving an output saying: Good job! You guessed correct. But whenever you guess the correct answer it doesn't show the output as I want it to. Am I making a silly error or is it something else? following is the code:
import random
range_1 = int(input("Enter your first range: "))
range_2 = int(input("Enter your second range: "))
x = random.randint(range_1, range_2)
print("Number chosen!")
guess = int(input(f"Guess the answer between {range_1} and {range_2}: "))
while guess != x:
if guess > x:
guess = int(input("Go lower: "))
elif guess < x:
guess = int(input("Go higher: "))
else:
print("Good job! You guessed correct!")
Upvotes: 0
Views: 35
Reputation: 6378
Fine job mate :)
Just put it after the loop, because when condition is met: guess == x
it will not stay in the loop to get it in elif
.
while guess != x:
if guess > x:
guess = int(input("Go lower: "))
elif guess < x:
guess = int(input("Go higher: "))
print("Good job! You guessed correct!")
If you want it inside the loop badly, then you might go with:
while guess != x:
if guess > x:
guess = int(input("Go lower: "))
elif guess < x:
guess = int(input("Go higher: "))
if guess == x:
print("Good job! You guessed correct!")
Upvotes: 0
Reputation: 2561
you can`t reach the else of the print.
The while
loop check if guess is different than x, and the 2 if check if bigger or lower.
fix:
import random
range_1 = int(input("Enter your first range: "))
range_2 = int(input("Enter your second range: "))
x = random.randint(range_1, range_2)
print("Number chosen!")
guess = int(input(f"Guess the answer between {range_1} and {range_2}: "))
while guess != x:
if guess > x:
guess = int(input("Go lower: "))
elif guess < x:
guess = int(input("Go higher: "))
print("Good job! You guessed correct!")
Upvotes: 0
Reputation: 4772
The problem is that the "you guessed correct" statement is in the while loop. Once guess
has the correct value, the loop is exited and the print statement is never reached.
One fix is to put this print statement after the loop. Consider the following:
while guess != x:
if guess > x:
guess = int(input("Go lower: "))
elif guess < x:
guess = int(input("Go higher: "))
print("Good job! You guessed correct!")
Upvotes: 1