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.
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to