suffi suffi - 1 year ago 51
Python Question

How to cleanly ask user for input and allow several types?

So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the number of names and greater than 0.

while True:
number = str(input("Enter number, or q to quit. \n"))
if number == "q":
number = int(number)
if number <= len(list_of_names) and number > 0:
name = list_of_names[number-1]

There is no problem with this code, except I find it hard to read, and not very beautiful. Since I am new to python I would like to ask you guys, how would you code this prompt more cleanly? To be more specific: How do I ask the user for input that can be either a string, or an integer?

Answer Source

A bit simpler:

while True:    
    choice = str(input("Enter number, or q to quit. \n"))
    if choice.lower() == "q":
    elif choice.isdigit() and (0 < int(choice) <= len(list_of_names)):
        name = list_of_names[int(choice)-1]