代码之家  ›  专栏  ›  技术社区  ›  maira

在处理可能引发异常的输入时,如何使用while循环?

  •  0
  • maira  · 技术社区  · 2 年前

    我正在为我的uni项目编写代码,这一部分要求用户输入一个文件名,当找不到文件名时,它应该显示一条消息,然后提示用户显示一个有效的文件名。这是我到目前为止所做的,但它在第二次无效输入后停止,我不确定如何使用while循环。如果有人能帮忙,那就太好了。非常感谢。

    if user_choice == commands[2]: 
        try:
            file_name = input("Enter file name: ")
            print(INPUT(file_name))
    
        except FileNotFoundError:
            print("The file name you entered does not exist.")
            file_name = input("Enter file name: ")
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   António Rebelo    2 年前

    您只需创建一个while循环,并在找到文件时中断。所以应该是这样的:

    if user_choice == commands[2]: 
        while True:
            try:
                file_name = input("Enter file name: ")
                print(INPUT(file_name))
                #if the file is found (if statement) (I don't know how you would do this as i haven't seen the full code):
                    break
    
            except FileNotFoundError:
                print("The file name you entered does not exist.")
                file_name = input("Enter file name: ")
    
        2
  •  0
  •   Jérémie    2 年前

    试试这样:

    if user_choice == commands[2]: 
    
    var = 0
    while var != 1 :
      try:
            file_name = input("Enter file name: ")
            print(INPUT(file_name))
            var = 1
    
        except FileNotFoundError:
            print("The file name you entered does not exist.")
            file_name = input("Enter file name: ")