简体   繁体   中英

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().

The break on the function does not have effect on your while loop, try returning True and checking the return value on each iteration:

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.

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

while True:
    main():
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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