string - Checking that input is an integer between 1 and 3 - Python -


this question has answer here:

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

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -