相当于python中的GOTO

The equivalent of a GOTO in python

本问题已经有最佳答案,请猛点这里访问。

我正在自学python 2.7。 我在使用具有GOTO语句的BATCH方面有一些经验。 我该如何在python中做到这一点? 例如,假设我要从第5行跳到第18行。

我意识到以前有关于此主题的问题,但是我发现它们没有足够的信息,或者对于我目前的理解而言,对于python来说太高了。


原谅我-我无法抗拒;-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def goto(linenum):
    global line
    line = linenum

line = 1
while True:
    if line == 1:
        response = raw_input("yes or no?")
        if response =="yes":
            goto(2)
        elif response =="no":
            goto(3)
        else:
            goto(100)
    elif line == 2:
        print"Thank you for the yes!"
        goto(20)
    elif line == 3:
        print"Thank you for the no!"
        goto(20)
    elif line == 20:
        break
    elif line == 100:
        print"You're annoying me - answer the question!"
        goto(1)


goto在计算机科学和编程中普遍受到谴责,因为它们会导致非常非结构化的代码。

Python(像当今几乎所有编程语言一样)都支持结构化编程,该结构使用if / then / else,循环和子例程控制流。

以结构化方式进行思考的关键是理解如何以及为什么要分支代码。

例如,让我们假装Python有一个goto和相应的label语句抖动。看下面的代码。如果数字大于或等于0,则在其中打印

1
2
3
4
5
6
7
8
9
10
11
number = input()
if number < 0: goto negative
if number % 2 == 0:
   print"even"
else:
   print"odd"
goto end
label: negative
print"negative"
label: end
print"all done"

如果我们想知道何时执行一段代码,则需要仔细地在程序中进行追溯,并检查标签是如何到达的-这实际上是做不到的。

例如,我们可以将以上内容重写为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
number = input()
goto check

label: negative
print"negative"
goto end

label: check
if number < 0: goto negative
if number % 2 == 0:
   print"even"
else:
   print"odd"
goto end

label: end
print"all done"

在这里,有两种可能的方法可以到达"终点",我们不知道选择了哪一个。随着程序变大,这种问题变得更加严重,并导致产生意大利面条式代码

相比之下,下面是用Python编写该程序的方式:

1
2
3
4
5
6
7
8
9
number = input()
if number >= 0:
   if number % 2 == 0:
       print"even"
   else:
       print"odd"
else:
   print"negative"
print"all done"

我可以查看特定的代码行,并通过追溯其所在的if/then/else块树来了解在什么条件下可以满足它。例如,我知道当


我完全同意goto的编码不好,但是实际上没有人回答过这个问题。实际上,有一个用于Python的goto模块(尽管它是愚人节玩笑发布的,不建议使用,但它确实可以工作)。


Python编程语言中没有goto指令。您必须以结构化的方式编写代码...但是,实际上,为什么要使用goto?几十年来一直被认为是有害的,并且您可以想到的任何程序都可以在不使用goto的情况下编写。

当然,在某些情况下无条件跳转可能很有用,但它不是强制性的,总会存在不需要goto的语义等效的结构化解决方案。


免责声明:我接触了大量的F77

goto的现代等效项(可以争论,只有我自己的观点,等等)是显式异常处理:

编辑以突出代码重用性更好。

goto将伪代码伪装成类似python的伪语言:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def myfunc1(x)
    if x == 0:
        goto LABEL1
    return 1/x

def myfunc2(z)
    if z == 0:
        goto LABEL1
    return 1/z

myfunc1(0)
myfunc2(0)

:LABEL1
print 'Cannot divide by zero'.

与python相比:

1
2
3
4
5
6
7
8
9
10
11
12
def myfunc1(x):
    return 1/x

def myfunc2(y):
    return 1/y


try:
    myfunc1(0)
    myfunc2(0)
except ZeroDivisionError:
    print 'Cannot divide by zero'

显式命名异常是处理非线性条件分支的一种更好的方法。


1
2
3
4
5
answer = None
while True:
    answer = raw_input("Do you like pie?")
    if answer in ("yes","no"): break
    print"That is not a yes or a no"

无需goto语句即可为您提供所需的内容。