How to break a Python while loop from a function within the loop

后端 未结 5 1538
时光说笑
时光说笑 2021-01-15 03:05
while True:
    input = raw_input(\"enter input: \")
    result = useInput(input)

def useInput(input):
    if input == \"exit\":
        break   #return 0 / quit /          


        
5条回答
  •  攒了一身酷
    2021-01-15 03:34

    Well if its just aesthetics thats keeps you from putting it in the while loop then any of the above would work... not of fan of the try/except one though. Just know there isn't going to be any performance difference putting it in its own function though. Here's one that I believe also meets your requirements :-)

    # you have to define the function first if your while isn't in a function
    def UseInput():
       input = raw_input("enter input: ")
       if input == "exit":
          return False
       elif input == "pass":
          return True
    
    
       # Do stuff
       return True
    
    
    while UseInput():
       pass
    

提交回复
热议问题