0

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?

Timur Shtatland
  • 9,559
  • 2
  • 24
  • 32
Zack Plauché
  • 1,964
  • 9
  • 24
  • 3
    Using a conditional expression like that is pretty unidiomatic. Which version of Python, can you use `while answer := input(input_prefix):` (available from 3.8, see [PEP 572](https://www.python.org/dev/peps/pep-0572/))? – jonrsharpe Jan 06 '21 at 14:40
  • @jonrsharpe yep! I'm on Pyhton 3.8+. That worked like a charm! Beautiful solution. – Zack Plauché Jan 06 '21 at 14:43

3 Answers3

1

Use the code below. I also added a few minor tweaks for more Pythonic code:

def answer_as_ul(question, input_prefix='• '):
    print(question)
    answer_list = []
    while True:
        answer = input(input_prefix)
        if not answer: break
        answer_list.append(answer)
    return answer_list
Timur Shtatland
  • 9,559
  • 2
  • 24
  • 32
1

Maybe like this but it doesn't make a lot of difference :

def answer_as_ul(question, input_prefix='• '):
    print(question)
    answer_list = list()
    while True:
        answer = input(input_prefix)
        if answer: break  
        else: answer_list.append(answer)
    return answer_list
dspr
  • 2,268
  • 2
  • 14
  • 17
1

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
Zack Plauché
  • 1,964
  • 9
  • 24