簡體   English   中英

獲取用戶輸入為int或str

[英]Get user input as int or str

我對python還是很陌生,並且相信我,我一直在尋找解決方案,但是我無法理解。

我有一個帶有監視圖列表的csv。 使用下面的代碼,我已經能夠顯示2dlist並讓用戶輸入一個數字,以基於列表索引來選擇特定的繪圖(其中有11個)。

但是,當提示用戶選擇時,我想添加一個選項“ ....或按'q'退出”。 現在顯然raw_input設置為僅接收整數,但是我如何從列表或'q'中接受數字?

如果我從raw_輸入中刪除“ 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"
choice = raw_input("Select a monitoring plot from the list: ")

if choice == 'q':
    break

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

檢查用戶是否輸入q並明確地退出循環(而不是依賴於引發異常)。 此檢查后僅將其輸入轉換為int。

在檢查它不是'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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM