回到python中的一个破碎的循环

cod*_*guy 4 python loops python-3.x

在python中留下一个循环有2种不同的选项.continue,它会让你回到循环的开头,而break就像一个灯开关,它会在脚本运行的剩余时间内切断循环.我的问题是我有一段时间的True循环,我希望能够突破它,然后在代码中稍后返回它.这是可能的,如果是的话,我该怎么做?到目前为止,我有这样的事情:

while True
    if #condition:
        #do something
    else:
        #do something
        break
while True
    if #condition:
        #do something
    else:
        break
#code that returns it to the first loop
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,如破裂或什么?对不起,我是编程新手,这是我在计算机科学的第一年,我刚开始学习python.

小智 5

你可以把第一个循环放在一个函数中.

def first_loop():
    while True:
    if something:
        # do something
    else:
        break

# call loop for first time
first_loop()

while True:
    if something:
        #do something
    else:
        break

# return back to the loop
first_loop()
Run Code Online (Sandbox Code Playgroud)