【问题标题】:How to use except with numbers in my loop如何在我的循环中使用除了数字
【发布时间】:2025-11-30 22:40:01
【问题描述】:

我正在尝试编写一个简短的 python 脚本。 我的目标很简单:代码必须要求您在写“1”或“2”之间做出选择。如果选择 1,您将在控制台中获得一个列表;如果您写 2,您将获得一个 CSV 文件。此外,当您编写任何不是数字的内容时,代码会要求您再次编写。所以到目前为止所有这些函数都运行良好,问题是当你写任何其他不是 1 o 2 的数字时,脚本只会自行完成。 除了其他数字,我可以做些什么来包括?

这是脚本:

while True:
    try:
        answer = int(input("Press 1 to see protein ID in console \nPress 2 to export protein CSV list \nChoose="))
    except ValueError:
        print("Sorry, not what I was expecting \nTry again")
        continue
    else:
        break
if answer== 1:
    from ProteinHtmlID import ProteinHtmlID 

    if __name__ == "__main__":
        protein = ProteinHtmlID("protein.html") #name of the file you want check
        name = protein.getFileName()
        print(name)
    
        count = protein.searchProtein("Acidobacterium ailaaui")
        print(count)
    
        found = protein.findAllProteinNames()
        print(found)
elif answer== 2:
    import pandas as pd
    from ProteinHtmlID import ProteinHtmlID 
    
    #prot_name = ProteinHtmlID("protein.html")
    wp_num = ProteinHtmlID("protein.html")
    
    #found = prot_name.findAllProteinNames()
    found = wp_num.findAllProteinNames()
    
    #prot_name = []
    places = []
    wp_num = []
    
    for elem in found:
      #prot_name.append(elem)
      wp_num.append(elem)
      places.append(found[elem])
      
    
    #data = {'Name' : prot_name, 'Place' : places, 'ID' : wp_num}
    data = {'Place' : places, 'ID' : wp_num}
    dataframe = pd.DataFrame(data)
    df = pd.DataFrame(data)
    df.to_csv('chitin_names.csv', index=False)
    print(dataframe)

【问题讨论】:

    标签: python-3.x while-loop except


    【解决方案1】:

    如果用户输入的不是 1 或 2 的有效数字,您将不会得到 ValueError,因此脚本会简单地退出 while 循环。

    您可以在 try 块中添加检查以避免这种情况:

    if ans < 1 or ans > 2:
        continue
    

    【讨论】:

      【解决方案2】:

      由于除了检查错误之外,您不能轻易地包含 answer 是 1 或 2 的事实。相反,只需在 break 之前再做一次检查:

      while True:
          try:
              answer = int(input("Press 1 to see protein ID in console \nPress 2 to export protein CSV list \nChoose="))
          except ValueError:
              print("Sorry, not what I was expecting \nTry again")
              continue
          else: # Can't use elif on try...catch if I remember well
              if answer == 1 or answer == 2: # Check answer is 1 or 2. Otherwise, the loop continues
                  break
      

      注意这里同时使用continueelse是没有用的。

      顺便说一句,我宁愿把你的代码写成这样,我觉得它更简洁:

      while True:
          try:
              answer = int(input("Press 1 to see protein ID in console \nPress 2 to export protein CSV list \nChoose="))
              if answer == 1 or answer == 2:
                  break
          except ValueError:
              pass
          print("Sorry, not what I was expecting \nTry again")
      

      只有当answer 是 1 或 2 时才停止循环,否则继续循环,然后在循环的后面编写错误消息。 (except ValueError: pass 允许继续循环,就好像没有ValueError)。

      【讨论】: