Get user input as int or str

2019-02-27 17:50发布

问题:

I'm very new to python and believe me, I've searched endlessly for a solution to this but I just can't get it.

I have a csv with a list of monitoring plots. With the code below, I have been able to display the 2dlist and get the user to enter a number to choose a particular plot (there's 11 of them), based on the list index.

But when prompting the user to choose, I'd like to include an option '....or press 'q' to quit'. Now obviously raw_input is set to receive integers only but how can I accept a number from the list or 'q'?

If I remove 'int' from raw_ input, it keeps prompting to enter again, printing the exception line. Can I get it to accept the index numbers (0-9) OR 'q'?

for item in enumerate(dataList[1:]):            
    print "[%d] %s" % item

while True:
    try:
        plotSelect = int(raw_input("Select a monitoring plot from the list: "))
        selected = dataList[plotSelect+1]

        print 'You selected : ', selected[1]
        break
    except Exception:
        print "Error: Please enter a number between 0 and 9"

回答1:

Convert it into an integer after you check that it's not 'q':

try:
    response = raw_input("Select a monitoring plot from the list: ")

    if response == 'q':
        break

    selected = dataList[int(plotSelect) + 1]

    print 'You selected : ', selected[1]
    break
except ValueError:
    print "Error: Please enter a number between 0 and 9"


回答2:

choice = raw_input("Select a monitoring plot from the list: ")

if choice == 'q':
    break

plotSelect = int(choice)
selected = dataList[plotSelect+1]

Check if the user entered q and explicitly break out of the loop if they do (rather than relying on an exception being thrown). Only convert their input an int after this check.