2013-04-21 56 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