如何在我的循环中使用 except with numbers

How to use except with numbers in my loop

我正在尝试编写一个简短的 python 脚本。 我的 objective 很简单:代码必须要求您在写“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)

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

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

if ans < 1 or ans > 2:
    continue

因为 except 检查错误,你不能轻易地包含 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 一样)。