我對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"
謝謝兩位。這完全按照我想要的方式工作 – 2013-04-21 01:14:41