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

后端 未结 5 1539
时光说笑
时光说笑 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:42

    You can raise an exception and handle it outside of while ... but that will likely result in some confusing code ...

    def useInput(in_):
        if in_ == "exit":
            raise RuntimeError
    try:
        while True:
            input = raw_input("enter input: ")
            result = useInput(input)
    
    except RuntimeError:
        pass
    

    It's MUCH better to just return a boolean flag and then break or not depending on the value of that flag. If you're worried that you already have something you want to return, don't fret -- python will happily let your function return more than one thing:

    def func()
        ...
        return something,flag
    
    while True:
        something,flag = func()
        if flag:
            break
    

提交回复
热议问题