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

查看:24
本文介绍了获取用户输入为 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_ 输入中删除 '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天全站免登陆