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.
def input_until(message, func):
"""Take raw input from the user (asking with the given message), until
when func is applied it returns True."""
while True:
value = raw_input(message)
if func(value):
return
else:
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
:
def call_repeatedly(func, *args, **kwargs):
while True:
yield func(*args, **kwargs)
for value in itertools.takewhile(lambda x: x != "exit",
call_repeatedly(raw_input, "enter input: ")):
...