2

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?

Boran
  • 37
  • 1
  • 6
  • Any coding has an integer number of characters, so mathematically: yes there must be a minimal code. – Julien Oct 08 '18 at 06:00

2 Answers2

4

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.")
blhsing
  • 91,368
  • 6
  • 71
  • 106
0
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

bipin_s
  • 455
  • 3
  • 15
  • `int(input())` will not crash the program. Ran the above program:: `Enter a number between 1 and 100: kjghfsgf Input must be an integer between 1 and 100. Enter a number between 1 and 100:` – raja777m Jun 13 '20 at 13:55
  • I've further improved my answer if you are interested. And no, my original answer would not have crashed on string input either. – blhsing Sep 17 '22 at 19:28