【问题标题】:Get user input as int or str获取用户输入为 int 或 str
【发布时间】:2013-04-14 03:42:10
【问题描述】:

我对 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"

【问题讨论】:

    标签: python string input int 2d


    【解决方案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"
    

    【讨论】:

      【解决方案2】:
      choice = raw_input("Select a monitoring plot from the list: ")
      
      if choice == 'q':
          break
      
      plotSelect = int(choice)
      selected = dataList[plotSelect+1]
      

      检查用户是否输入了q,如果输入则显式地跳出循环(而不是依赖于抛出的异常)。仅在此检查后将其输入转换为 int。

      【讨论】:

      • 哎呀,现在我意识到如果输入的数字超出范围 (0-9),我不会收到 ValueError 消息
      猜你喜欢
      • 2010-12-23
      • 2020-07-28
      • 2021-11-15
      • 2020-05-11
      • 1970-01-01
      • 2022-11-15
      • 2018-07-07
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多