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

Question:

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?

Asked By: Boran

||

Answers:

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.")
Answered By: blhsing
while True:
  try:
    number = raw_input("Enter a number between 1 and 100: ")
    if number.isdigit():
       number=int(number)
    else:   
       raise ValueError()
    if 1 <= number <= 100:
        break
    raise ValueError()
  except ValueError:
    print("Input must be an integer between 1 and 100.")

it is a small improvement over the answer by @blhsing , so that the program does not crash on string input

Answered By: bipin_s