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


当前回答

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

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

其他回答

不,有另一种方法来实现goto语句

class id:
     def data1(self):
        name=[]
        age=[]   
        n=1
        while n>0:
            print("1. for enter data")
            print("2. update list")
            print("3. show data")
            print("choose what you want to do ?")
            ch=int(input("enter your choice"))
            if ch==1:    
                n=int(input("how many elemet you want to enter="))
                for i in range(n):
                    name.append(input("NAME "))
                    age.append(int(input("age "))) 
            elif ch==2:
                name.append(input("NAME "))
                age.append(int(input("age ")))
            elif ch==3:
                try:
                    if name==None:
                        print("empty list")
                    else:
                        print("name \t age")
                        for i in range(n):
                            print(name[i]," \t ",age[i])
                        break
                except:
                    print("list is empty")
            print("do want to continue y or n")
            ch1=input()
            if ch1=="y":
                n=n+1
            else:
                print("name \t age")
                for i in range(n):
                    print(name[i]," \t ",age[i])
                n=-1
p1=id()
p1.data1()  

使用评论中@bobince的建议来回答@ascobol的问题:

for i in range(5000):
    for j in range(3000):
        if should_terminate_the_loop:
           break
    else: 
        continue # no break encountered
    break

else块的缩进是正确的。代码在循环Python语法后使用模糊的else。参见为什么python在for和while循环之后使用'else' ?

我在官方的python设计和历史FAQ中找到了这个。

为什么没有goto? 您可以使用异常来提供一个甚至可以工作的“结构化goto” 跨函数调用。许多人认为异常可以方便地实现 模拟C语言中“go”或“goto”结构的所有合理使用, Fortran和其他语言。例如:

class label(Exception): pass  # declare a label

try:
    ...
    if condition: raise label()  # goto label
    ...
except label:  # where to goto
    pass
... 

这并不允许你跳到循环的中间,但那是 通常被认为是对goto的滥用。很少使用。

在官方常见问题解答中甚至提到了这一点,并且提供了一个很好的解决方案示例,这非常好。我真的很喜欢python,因为它的社区甚至是这样对待goto的;)

我最近写了一个函数装饰器,在Python中启用goto,就像这样:

from goto import with_goto

@with_goto
def range(start, stop):
    i = start
    result = []

    label .begin
    if i == stop:
        goto .end

    result.append(i)
    i += 1
    goto .begin

    label .end
    return result

我不知道为什么有人想做这样的事情。也就是说,我并不是很认真。但我想指出的是,这种元编程在Python中实际上是可能的,至少在CPython和PyPy中是可能的,而不仅仅是像其他人那样误用调试器API。不过,您必须修改字节码。

虽然在Python中没有任何等同于goto/label的代码,但您仍然可以使用循环来获得goto/label的这种功能。

让我们以下面所示的代码示例为例,其中goto/label可以在python以外的任意语言中使用。

String str1 = 'BACK'

label1:
    print('Hello, this program contains goto code\n')
    print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
    str1 = input()

if str1 == 'BACK'
    {
        GoTo label1
    }
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

现在,通过使用下面所示的while循环,可以在python中实现上述代码示例的相同功能。

str1 = 'BACK'

while str1 == 'BACK':
        print('Hello, this is a python program containing python equivalent code for goto code\n')
        print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
        str1 = input()
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')