I’m working on a high/low number guessing game, I’m running into two issues.
- I can’t figure out how to reuse/reprompt for user input.
- The user input is getting stuck in an infinite loop that I’m not sure how to fix.
import random
high_number = int(input('Enter your high number!\n'))
low_number = int(input('Enter your low number!\n'))
if low_number >= high_number:
print('Your low number must be less than your high number!')
else:
random_number = random.randint(low_number, high_number)
user_guess = int(input(f'Guess a number between {low_number} and {high_number}\n'))
while user_guess != random_number:
if user_guess > random_number:
print('Guess too high, guess another number!')
elif user_guess < random_number:
print('Guess too low, guess another number!')
if user_guess == random_number:
print('You guessed it right!')
>Solution :
You need to think about how things flow, from top to bottom. If they enter the numbers in the wrong order, you print the error, but you keep going into the game without asking for a guess. And your loop just prints forever, without asking for another guess.
This basically works. Note the philosophy of the "ask for info" loops. Do while True, then if the input is OK, you break from the loop. Otherwise, print an error and the loop will cycle again.
import random
while True:
high_number = int(input('Enter your high number!\n'))
low_number = int(input('Enter your low number!\n'))
if low_number < high_number:
break
print('Your low number must be less than your high number!')
random_number = random.randint(low_number, high_number)
while True:
user_guess = int(input(f'Guess a number between {low_number} and {high_number}\n'))
if user_guess == random_number:
print('You guessed it right!')
break
if user_guess > random_number:
print('Guess too high, guess another number!')
elif user_guess < random_number:
print('Guess too low, guess another number!')