Search code examples
pythonpython-3.xwhile-loopwalrus-operator

Is there a way to do a while loop on a variable that's undefined? (How can I rewrite this, Python)


I want to do a while loop that runs until a user puts nothing in the input.

This is what I have that currently works, but I want to remove the answer = None instantiation.

def answer_as_ul(question, input_prefix='• '):
    print(question)
    answer_list = list()
    answer = None
    while answer != '':
        answer = input(input_prefix)
        answer_list.append(answer) if answer else None
    return answer_list

Is there a way to remove answer = None here and keep the functionality?


Solution

  • I found the answer thanks to @jonsharpe's beautiful solution using Python 3.8's walrus operator:

    def answer_as_ul(question, input_prefix='• '):
        print(question)
        answer_list = list()
        while answer := input(input_prefix):
            answer_list.append(answer)
        return answer_list