Python中条件的GOTO等效项
因为Python里没有goto这个操作符,那我们可以用什么方法来代替呢?
条件判断:如果条件成立,就去执行第一个线程;如果条件不成立,就去执行第二个线程。在第一个线程里,我们做一些小事情,之后再去第二个线程,那里会进行其他所有的操作。
5 个回答
5
根据我所知道的,这个东西是不存在的(谢天谢地),不过你可以看看这个链接
“goto”模块其实是个愚人节玩笑,发布于2004年4月1日。没错,它确实能工作,但它就是个玩笑。请不要在真正的代码中使用它!
6
def thread_1():
# Do thread_1 type stuff here.
def thread_2():
# Do thread_2 type stuff here.
if condition:
thread_1()
# If condition was false, just run thread_2().
# If it was true then thread_1() will return to this point.
thread_2()
补充说明:我假设你所说的“线程”是指一段代码(也就是子程序或函数)。如果你是在谈论并行执行的线程,那你需要在问题中提供更多细节。
14
因为Python没有goto这个操作符,那我们可以用什么方法来代替呢?
可以通过合理地组织你的代码来实现。
if condition:
perform_some_action()
perform_other_actions()