简体   繁体   English

如何打破这个while循环?

[英]How to break this while loop?

def left():
    print("left")
def right():
    print("right")
def main():
    command = input ("Enter your command: ")
    if command == "left":
        left()
    if command == "right":
        right()
    if command ==  "done":
        break
while True:
    main()

I don't understand how to break out of this while loop while calling the main function.I am trying to break out of the while loop while calling the function main().我不明白如何在调用主 function 时跳出这个 while 循环。我试图在调用 function main() 时跳出 while 循环。

The break on the function does not have effect on your while loop, try returning True and checking the return value on each iteration: function 上的中断对您的 while 循环没有影响,请尝试返回True并检查每次迭代的返回值:

def main():
    command = input ("Enter your command: ")
    if command == "left":
        left()
    elif command == "right":
        right()
    elif command ==  "done":
        return True
while True:
    if main():
        break

the answer from Pedro Maia is the best one, but you can also call exit() if you are sure that you will end your process and will not leak memory in any way. Pedro Maia 的答案是最好的,但如果您确定将结束您的进程并且不会以任何方式泄漏 memory,您也可以调用exit()

def main():
    command = input ("Enter your command: ")
    if command == "left":
        left()
    elif command == "right":
        right()
    elif command ==  "done":
        exit()

while True:
    main():
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM