Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to re-prompt input in Python & fix infinite loop in high/low number guessing game

I’m working on a high/low number guessing game, I’m running into two issues.

  1. I can’t figure out how to reuse/reprompt for user input.
  2. 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading