[Tutor] How to handle a non integer within a question function that needs to return a integer?

Wibble saphirmartin at gmail.com
Wed Mar 11 22:26:38 CET 2015


Dear All

Very basic question from a newbie.

I have defined a function for asking a question within a range

def user_choice(question, low, high, step = 1):
     """Define user choice"""
     choice = None
     while choice not in range(low, high, step):
         choice = int(input(question))
     return choice

If user enters a string rather than a number it creates this error

Traceback (most recent call last):
   File "/home/wibble/bhdevices.py", line 100, in <module>
     choice = user_choice("Choose an option: ", 0, CHOICES)
   File "/home/wibble/bhdevices.py", line 53, in user_choice
     choice = int(input(question))
ValueError: invalid literal for int() with base 10: 'd'

How do I make it show a message to users saying only numbers excepted 
and then the loop continues?

I have tried this but same error is still generated.

def user_choice(question, low, high, step = 1):
     """Define user choice"""
     choice = None
     while choice not in range(low, high, step):
         choice = int(input(question))
         if choice == str(input(question)):
             print('Numbers only please!')
     return choice

Do I need to create another while loop within this loop to handle a 
string input?

Any assistance would be greatly appreciated.

Kind regards

Andrew.


More information about the Tutor mailing list