user2527918 user2527918 - 8 months ago 35
Python Question

number lists in Python

I am allowing choices to user and if the user's choice isn't a number then the script should show an error message: "Please try again".

def prompt(message, choices):
while True:
choice = input(message)
if choice in choices:
return choice
print("That was not a valid answer. please retry\n"
"valid answers are", choices)

def aORp():
choices = list(range(1, 17))
length= prompt("What is your length? ",choices)


You can write a function which inputs a number and then converts it to an int, but doesn't work if it is anything else. If I understand you right, you only want the user to be able to enter an int but not a string. If you only want to check that, an example is:

def prompt (message):
        choice = int(input(message))
        return choice
    except ValueError:
        print("That is not a valid answer, please try again.")
        return prompt(message)

That's generally how I do it, but you can definitely use a while loop if you want.