如何在Python中“break”if语句

2024-10-03 09:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我代码的一小部分

def menu():
    choices = ["Create a Scenario", "Load a Database", "Quit"]
    m1 = eg.choicebox("What would you like to do?", "Greenfly Model Menu", choices)
    if m1 == "Load a Scenario":
        dbless = eg.enterbox("What is the name of your database?")
        if dbless is None:
            menu()
        db_name = dbless + ".db"
        check = os.path.isfile(db_name) 

如果变量dbless最终为None,则代码将按其假设运行menu()函数。但是,当代码的其余部分执行完毕时,该函数的其余部分将结束运行。有没有办法让它的其余部分不运行。在


Tags: 函数代码namenonedbifisload
3条回答

使用return语句,而不是在没有循环的函数内考虑break。在

您可以包含一个while循环,以便在输入不是None之前,它将请求输入:

while dbless is None:
    menu()
else:  #you can remove the else and unindent the next two lines, but I'm used to do it that way
    db_name = dbless + ".db"
    check = os.path.isfile(db_name)

我在这里看到的问题是它将无限期地请求输入。如果您对此有问题,您可以在while中添加一个attempt之类的东西,但我认为情况并非如此。另外,我不确定代码是否真的会因为再次调用函数而工作。。。不管怎样,试试看。在

不应该在循环之外使用break语句。因此,您需要使用return语句。你可以用两种方法。在

if dbless is None:
    menu()
    return 

或者

^{pr2}$

相关问题 更多 >