【问题标题】:Break out of outer function if condition in inner function fails如果内部函数中的条件失败,则退出外部函数
【发布时间】:2021-07-19 08:19:03
【问题描述】:

我有一个函数move() 的代码很长,运行时间超过一分钟,在此期间执行该函数的条件可能不再为真。起初,我正在寻找一些东西来在执行每一行新代码之前检查该语句是否正确,但显然不存在(超级奇怪)。

我的新想法如下:

def breakk():
    if x==0 or y == 0 or z == 0:
        code
        code
        code
        return 

def move():
    if x==1 and y == 1 and z == 1: 
        code
        code
        breakk()
        code
        code
        breakk()
        code

但这不起作用,因为内部函数breakk()中的return对外部函数move()没有影响

我目前的工作很糟糕.. :

breakkk=0
def breakk():
    global breakkk
    if x==0 or y == 0 or z == 0:
        code
        code
        code
        breakkk=1
         

def move():
    global breakkk
    if x==1 and y == 1 and z == 1: 
        code
        code
        breakk()
        if breakkk==1:
            breakkk=0
            return
        code
        code
        breakk()
        if breakkk==1:
            breakkk=0
            return
        code
        .....

move()

【问题讨论】:

  • 我不太理解这个问题,但为什么不在breakk 函数中返回一个布尔值,然后只使用if breakk(): return?我还建议避免使用全局变量,只需在 breakk 函数中将变量作为参数传递即可。像...if breakk(x, y, z): return.
  • 如果有意义的话,另一种可能性是引发异常。通过引发异常,您可以“跳出”任何函数,无论其调用嵌套多深,但随后您必须在希望异常停止冒泡的任何级别添加适当的异常处理代码。

标签: python return break


【解决方案1】:

breakk()返回一个boolean,然后检查breakk()是否为true

def move():
    if x==1 and y == 1 and z == 1: 
        code
        code
        if breakk():
            return
        code
        code
        if breakk():
            return
        code

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2018-10-12
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多