我对 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"
最佳答案
确认不是'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"
关于python - 获取 int 或 str 形式的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126769/