在Python中是否有goto或任何等价的东西能够跳转到特定的代码行?


当前回答

早在2007年,PEP 3136就提出了中断和继续的标签,但被拒绝了。提案的动机部分说明了在Python中模仿带标签的break的几种常见方法(虽然不太优雅)。

其他回答

我在找一些类似的东西

for a in xrange(1,10):
A_LOOP
    for b in xrange(1,5):
        for c in xrange(1,5):
            for d in xrange(1,5):
                # do some stuff
                if(condition(e)):
                    goto B_LOOP;

所以我的方法是使用一个布尔值来帮助打破嵌套的for循环:

for a in xrange(1,10):
    get_out = False
    for b in xrange(1,5):
        if(get_out): break
        for c in xrange(1,5):
            if(get_out): break
            for d in xrange(1,5):
                # do some stuff
                if(condition(e)):
                    get_out = True
                    break

对于一个向前的后藤,你可以添加:

while True:
  if some condition:
    break
  #... extra code
  break # force code to exit. Needed at end of while loop
#... continues here

但这只适用于简单的场景(即嵌套这些会让你陷入混乱)

你可以使用用户定义异常来模拟goto

例子:

class goto1(Exception):
    pass   
class goto2(Exception):
    pass   
class goto3(Exception):
    pass   


def loop():
    print 'start'
    num = input()
    try:
        if num<=0:
            raise goto1
        elif num<=2:
            raise goto2
        elif num<=4:
            raise goto3
        elif num<=6:
            raise goto1
        else:
            print 'end'
            return 0
    except goto1 as e:
        print 'goto1'
        loop()
    except goto2 as e:
        print 'goto2'
        loop()
    except goto3 as e:
        print 'goto3'
        loop()

你可以使用python中的嵌套方法来实现

def func1():
    print("inside func1")
    def inline():
        print("im inside")
    
    inline()
    
func1()

为了代替python的goto等效,我以以下方式使用break语句快速测试我的代码。这里假设您有结构化的代码库。测试变量在函数开始时初始化,我只是将“If test: break”块移动到我想测试的嵌套If -then块或循环的末尾,在代码末尾修改返回变量以反映我正在测试的块或循环变量。

def x:
  test = True
  If y:
     # some code
     If test:
            break
  return something