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

Alan Gauld alan.gauld at btinternet.com
Thu Mar 12 01:50:07 CET 2015


On 11/03/15 21:26, Wibble wrote:

> 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):...
>      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?

Use a try/except construct inside your while loop.
Something like (untested):

def user_choice(question, low, high, step = 1):
     """Define user choice"""
     choice = None
     while choice not in range(low, high, step):
        try:
           choice = int(input(question))
        except ValueError:
           print("You must enter a number between ",low," and ", high)
     return choice

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list