string - Checking that input is an integer between 1 and 3 - Python -
this question has answer here:
- asking user input until give valid response 10 answers
i want able check input integer between 1 , 3, far have following code:
userchoice = 0 while userchoice < 1 or userchoice > 3: userchoice = int(input("please choose number between 1 , 3 > "))
this makes user re-enter number if not between 1 , 3, want add validation ensure user cannot enter string or unusual character may result in value error.
catch valueerror
:
raised when built-in operation or function receives argument has right type inappropriate value
example:
while userchoice < 1 or userchoice > 3: try: userchoice = int(input("please choose number between 1 , 3 > ")) except valueerror: print('we expect enter valid integer')
actually, since range of allowed numbers small, can operate directly on strings:
while true: num = input('please choose number between 1 , 3 > ') if num not in {'1', '2', '3'}: print('we expect enter valid integer') else: num = int(num) break
Comments
Post a Comment