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)
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"
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"
我完全同意
goto
是糟糕的编码,但是没有人真正回答这个问题。实际上是一个goto module for Python(虽然它是作为愚人节玩笑发布的,不推荐使用,但它确实有效)。原谅我-我无法抗拒;-)
Goto
s在计算机科学和编程中普遍受到抨击,因为它们导致非常非结构化的代码。Python(和现在几乎所有的编程语言一样)支持structured programming,它使用if/then/else、循环和子例程控制流。
以结构化的方式思考的关键是理解如何以及为什么在代码上进行分支。
例如,让我们假设Python有一个
goto
和相应的label
语句。请看下面的代码。如果一个数字大于或等于0,我们会打印如果我们想知道一段代码何时被执行,我们需要仔细地在程序中进行回溯,并检查标签是如何到达的——这是不可能真正做到的。
例如,我们可以将上述内容重写为:
在这里,有两种可能的方法可以达到“结束”,我们不知道选择了哪一种。当程序变大时,这种问题会变得更糟,并导致spaghetti code
相比之下,下面是您如何用Python编写这个程序:
我可以查看一行特定的代码,并通过追溯它所在的
if/then/else
块的树来知道在什么条件下满足它。例如,我知道print "odd"
行将在((number >= 0) == True) and ((number % 2 == 0) == False)
时运行。相关问题 更多 >
编程相关推荐