2013-04-21 57 views
1

我对python非常陌生并相信我,我已经无休止地寻找解决方案,但我无法得到它。获取用户输入为int或str

我有一个csv与监控图的列表。使用下面的代码,我能够显示2dlist并让用户输入一个数字,以根据列表索引选择一个特定的图(其中有11个)。

但是,当提示用户选择,我想包括一个选项'....或按'q'退出'。现在很明显raw_input被设置为只接收整数,但我怎么接受列表中的数字或'q'?

如果我从raw_ input中删除'int',它会一直提示再次输入,打印异常行。我可以让它接受索引号(0-9)或'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

将它转换成整数你检查之后,这不是'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" 
+0

谢谢两位。这完全按照我想要的方式工作 – 2013-04-21 01:14:41

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

if choice == 'q': 
    break 

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

检查用户输入q并明确退出循环,如果他们做的(而不是依赖于一个异常被抛出)。此检查后只能将其输入转换为int。

+0

哎呀,现在我才意识到,我没有得到消息ValueError异常,如果输入的数字超出范围(0-9) – 2013-04-21 01:56:30