简体   繁体   中英

I have a while loop that runs a function, how do I break out of the function after an if and return to the while loop?

I am trying to call a function inside an infinite loop. Once x happens in the function, I want it to return to the beginning of the while loop. How do you break out of the function?

I have tried to use break and return but, no luck.

def cmndln():
    while True:
        command = input("Input:> ")
        if command == 'exit':
            clientsocket.close()
            break

        elif command == 'decrypt':
            clientsocket.send("decrypt".encode())
            msg = clientsocket.recv(1024)
            print(msg.decode())
            key = input("Key: ")
            clientsocket.send(key.encode())
            msg = clientsocket.recv(1024)
            print(msg.decode())
            command = None
            break

        elif command == 'encrypt':
            clientsocket.send("encrypt".encode())
            msg = clientsocket.recv(1024)
            print(msg.decode())
            command = None
            break
    return

while True:
    cmndln()

I want to start the function again

def cmndln():
    command = input("Input:> ")
    if command == 'exit':
        clientsocket.close()

    elif command == 'decrypt':
        clientsocket.send("decrypt".encode())
        msg = clientsocket.recv(1024)
        print(msg.decode())
        key = input("Key: ")
        clientsocket.send(key.encode())
        msg = clientsocket.recv(1024)
        print(msg.decode())
        command = None

    elif command == 'encrypt':
        clientsocket.send("encrypt".encode())
        msg = clientsocket.recv(1024)
        print(msg.decode())
        command = None

def main():
    while True:
    #condition here
         cmndln()

if __name__ = '__main__':
     main()

Instead of the infinite loop twice you can call it once in the main function.

This way the command is still being called like before. You can now break on a condition in the main to exist the function.

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