【问题标题】:Why won't the function break out of this loop?为什么函数不会跳出这个循环?
【发布时间】:2022-01-02 11:39:36
【问题描述】:

我不知道为什么,但是我用于另一个程序的函数在遇到 FileNotFoundError 异常时不会跳出“while”循环。

import os
def delete_file(file_to_delete):
    try:
        os.remove(file_to_delete)
        print('file removed: ', file_to_delete)
        result = True
    except FileNotFoundError:
        print("Error. File not found.")
        result = False
        while result == False:
            if result == True: break
            input("Please enter a valid filename: ")
        os.remove(file_to_delete)
    return result

【问题讨论】:

  • 这是什么语言?
  • 哦,对了,我忘了。这是蟒蛇。
  • 您预计result 何时改变?
  • 该代码不是有效的python。请发布正确的minimal reproducible example
  • 对。 result 永不改变。这个逻辑很混乱。如果找不到文件,为什么要删除它?

标签: python while-loop break


【解决方案1】:

相反,删除 while 循环并更改逻辑以使其正常工作 -

import os
def delete_file(file_to_delete):
    result = False
    while result == False:
        try:
            os.remove(file_to_delete)
            print('file removed: ', file_to_delete)
            result = True

        except FileNotFoundError:
            print("Error. File not found.")
            file_to_delete = input('Please enter valid filename: ')
            
    return result

【讨论】:

  • 好的,但我还想包含一个提示,如果用户输入无效文件名,则特别要求用户输入“有效”文件名。
  • 这样更好。非常感谢你帮助我。
【解决方案2】:
result = False
while result == False:
    if result == True: break
    input("Please enter a valid filename: ")

循环不包含任何会改变result 值的东西,所以是的,这个循环将永远运行。

另外,对input() 的调用是无用的,因为您没有将结果保存在任何地方。

【讨论】:

  • 这是有道理的。谢谢。
【解决方案3】:

你怎么看这个逻辑?

import os

def delete_file(file_to_delete):
    while not os.path.isfile(file_to_delete):
        print("Error. File not found.")
        file_to_delete = input("Please enter a valid filename: ")
    
    os.remove(file_to_delete)
    print('file removed: ', file_to_delete)
    return True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多