在Python中是否有goto或任何等价的东西能够跳转到特定的代码行?
当前回答
你可以使用python中的嵌套方法来实现
def func1():
print("inside func1")
def inline():
print("im inside")
inline()
func1()
其他回答
使用评论中@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' ?
我用函数解决了这个问题。我唯一做的就是改变函数的标签。下面是一个非常基本的代码:
def goto_holiday(): #label: holiday
print("I went to holiday :)")
def goto_work(): #label: work
print("I went to work")
salary=5000
if salary>6000:
goto_holiday()
else:
goto_work()
我在找一些类似的东西
for a in xrange(1,10):
A_LOOP
for b in xrange(1,5):
for c in xrange(1,5):
for d in xrange(1,5):
# do some stuff
if(condition(e)):
goto B_LOOP;
所以我的方法是使用一个布尔值来帮助打破嵌套的for循环:
for a in xrange(1,10):
get_out = False
for b in xrange(1,5):
if(get_out): break
for c in xrange(1,5):
if(get_out): break
for d in xrange(1,5):
# do some stuff
if(condition(e)):
get_out = True
break
我想要同样的答案,我不想使用goto。所以我使用了下面的例子(来自learnpythonthehardway)
def sample():
print "This room is full of gold how much do you want?"
choice = raw_input("> ")
how_much = int(choice)
if "0" in choice or "1" in choice:
check(how_much)
else:
print "Enter a number with 0 or 1"
sample()
def check(n):
if n < 150:
print "You are not greedy, you win"
exit(0)
else:
print "You are nuts!"
exit(0)
Python 2和3
pip3 install goto-statement
在Python 2.6到3.6和PyPy上测试。
链接:转向语句
foo.py
from goto import with_goto
@with_goto
def bar():
label .bar_begin
...
goto .bar_begin