我自学了python 2.7.我有使用BATCH的经验,它有一个GOTO语句.我怎么在python中做到这一点?例如,假设我想从第5行跳到第18行.
我意识到之前有关于这个主题的问题,但我没有发现它们足够的信息,或者在我目前的理解中python级别太高.
小智 57
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"
Run Code Online (Sandbox Code Playgroud)
如果我们想知道何时执行一段代码,我们需要在程序中仔细追溯,并检查标签是如何到达的 - 这是无法真正完成的.
例如,我们可以将上面的内容重写为:
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"
Run Code Online (Sandbox Code Playgroud)
在这里,有两种可能的方式来达到"结束",我们无法知道选择了哪一种.随着程序变得越来越大,这种问题会变得更糟,并导致意大利面条代码
相比较而言,下面是你如何会在Python编写这个程序:
number = input()
if number >= 0:
if number % 2 == 0:
print "even"
else:
print "odd"
else:
print "negative"
print "all done"
Run Code Online (Sandbox Code Playgroud)
我可以查看特定的代码行,并通过追溯if/then/else它所在的块树来了解它在什么条件下被满足.例如,我知道该行将print "odd"在a时运行((number >= 0) == True) and ((number % 2 == 0) == False).
Tim*_*ers 57
原谅我 - 我无法抗拒;-)
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)
Run Code Online (Sandbox Code Playgroud)
sco*_*001 35
我完全同意这goto是糟糕的编码,但没有人真正回答过这个问题.还有就是其实是一个为Python转到模块(尽管它被发布了作为一个愚人节的玩笑,不建议使用,但不工作).
gotoPython编程语言中没有指令.你必须以结构化的方式编写代码......但实际上,你为什么要使用goto?几十年来一直被认为是有害的,任何你能想到的程序都可以在不使用的情况下编写goto.
当然,在某些情况下,无条件跳转可能是有用的,但它永远不是强制性的,总会存在一个不需要的语义等效的结构化解决方案goto.
免责声明:我接触过大量的F77
现代等价的goto(可论证的,只有我的观点等)是明确的异常处理:
编辑以更好地突出代码重用.
伪装成伪蟒蛇语言中的伪代码goto:
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'.
Run Code Online (Sandbox Code Playgroud)
与python相比:
def myfunc1(x):
return 1/x
def myfunc2(y):
return 1/y
try:
myfunc1(0)
myfunc2(0)
except ZeroDivisionError:
print 'Cannot divide by zero'
Run Code Online (Sandbox Code Playgroud)
显式命名异常是处理非线性条件分支的一种明显更好的方法.
| 归档时间: |
|
| 查看次数: |
289210 次 |
| 最近记录: |