获取用户输入为int或str [英] Get user input as int or str

查看:137
本文介绍了获取用户输入为int或str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python很新,相信我,我已经无休止地寻找解决方案,但我无法得到它。

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.

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

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.

但是当提示用户选择时,我想要包含一个选项'....或按'q'退出'。现在显然raw_input被设置为仅接收整数但是如何接受列表中的数字或'q'?

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'?

如果我从raw_ input中删除'int',它继续提示再次输入,打印例外行。我可以接受索引号(0-9)或'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"


推荐答案

在检查它不是'q'后将其转换为整数:

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"

这篇关于获取用户输入为int或str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆