Search code examples
pythonexceptionerror-handlinglimiting

Limiting an input between Two Numbers and checking if the input is a number or not at the same time


I have been trying to improve my guessing game in Python by limiting the guess input between 2 numbers(1 and 100) and asking if the guess input is a number or not. I have been trying to do this both at the same time. Is there anyway I can do this by minimum coding?


Solution

  • You can use a while loop to keep asking the user for a valid input until the user enters one:

    while True:
        try: 
            assert 1 <= int(input("Enter a number between 1 and 100: ")) <= 100:
            break
        except ValueError, AssertionError:
            print("Input must be an integer between 1 and 100.")