Skip to content Skip to sidebar Skip to footer

How To Break A Python While Loop From A Function Within The Loop

while True: input = raw_input('enter input: ') result = useInput(input) def useInput(input): if input == 'exit': break #return 0 / quit / etc.. i want to bre

Solution 1:

  1. Raise an exception, that you can handle outside the While loop
  2. Return a flag to be captured by the caller and handle accordingly. Note, "if logic" directly in the while loop,, would be the most preferred way.

Solution 2:

Python has a cool feature in generators - these allow you to easily produce iterables for use with a for loop, that can simplify this kind of code.

definput_until(message, func):
    """Take raw input from the user (asking with the given message), until 
    when func is applied it returns True."""whileTrue:
        value = raw_input(message)
        if func(value):
            returnelse:
            yield value

for value in input_until("enter input: ", lambda x: x == "exit"):
    ...

The for loop will loop until the iterator stops, and the iterator we made stops when the user inputs "exit". Note that I have generalised this a little, for simplicity, you could hard code the check against "exit" into the generator, but if you need similar behaviour in a few places, it might be worth keeping it general.

Note that this also means you can use it within a list comprehension, making it easy to build a list of results too.

Edit: Alternatively, we could build this up with itertools:

defcall_repeatedly(func, *args, **kwargs):
    whileTrue:
        yield func(*args, **kwargs)

for value in itertools.takewhile(lambda x: x != "exit", 
                                 call_repeatedly(raw_input, "enter input: ")):
    ...

Solution 3:

I usually do this:

defgetInput():
    whileTrue:
        yield raw_input("enter input: ")

forinputin getInput():
    ifinput == 'exit': 
        break
    result = useInput(input)

Solution 4:

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

defuseInput(in_):
    if in_ == "exit":
        raise RuntimeError
try:
    whileTrue:
        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

Solution 5:

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 functiondefUseInput():
   input = raw_input("enter input: ")
   ifinput == "exit":
      returnFalseelifinput == "pass":
      returnTrue# Do stuffreturnTruewhile UseInput():
   pass

Post a Comment for "How To Break A Python While Loop From A Function Within The Loop"