我在自学python2.7。我有一些使用批处理的经验,它有一个GOTO语句。在蟒蛇里我该怎么做呢?例如,假设我想从第5行跳到第18行。
我意识到以前有一些关于这个主题的问题,但是我发现它们没有足够的信息,或者说对于我目前的理解来说,python的水平太高了。
发布于 2013-09-18 03:35:47
Goto在计算机科学和编程中被普遍指责,因为它们导致了非常非结构化的代码。
Python (和现在几乎所有的编程语言一样)支持结构化编程,它使用if/then/else、循环和子例程来控制流。
以结构化方式思考的关键是理解如何以及为什么要在代码上进行分支。
例如,让我们假设Python有一个goto和相应的label语句。请看下面的代码。在它中,如果一个数字大于或等于0,我们打印如果它
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"在这里,有两种可能的方式来达到“结束”,我们不知道哪一个是被选择的。随着程序越来越大,这类问题会变得更糟,并在意大利面码中产生
相比之下,下面是如何用Python编写这个程序:
number = input()
if number >= 0:
if number % 2 == 0:
print "even"
else:
print "odd"
else:
print "negative"
print "all done"我可以查看特定的代码行,并通过追溯它所在的if/then/else块树来了解在什么条件下满足它。例如,我知道行print "odd"将在((number >= 0) == True) and ((number % 2 == 0) == False)时运行。
发布于 2013-09-18 03:45:38
原谅我-我忍不住;-)
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)发布于 2013-09-18 03:53:23
我完全同意goto编码不好,但没有人真正回答这个问题。实际上是一个Python的goto模块 (虽然它是作为愚人节玩笑发布的,不推荐使用,但它确实有效)。
https://stackoverflow.com/questions/18863309
复制相似问题