How to ask the user to input some specific integers? If I want to start with num = int(input("Enter a number here: ")) and the required numbers are integers from 1 to 5, when the user input anything else than 1, 2, 3, 4, and 5, the program will print “Incorrect value!” and repeat the prompt to ask the user to input a number until 1, 2, 3, 4 or 5 are entered, how should I achieve this?
The usual approach is to make an int from the input string as you’re
already doing, and then to compare that against the values you require
using a if-statement.
You could even be clever about it: most Python functions raise a
ValueError when handed an invalid value, as I imainge you’ve seen with
So you could catch an exception:
number_entry = input("Enter a number: ") try: number = int(number_entry) if test-for-invalid-number-here: raise ValueError("invalid number %d, should be in the range 1 through 5" % number) except ValueError as e: print("bad input:", e) else: do stuff with number here ...
Cameron Simpson email@example.com