我想做一个while循环,直到用户在输入中不输入任何内容。
这是我目前工作的内容,但我想删除answer = None
实例化。
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
有没有办法删除此处的answer = None
并保留其功能?
也许是这样,但没有太大区别:
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
使用下面的代码。我还为更多Python代码添加了一些小调整:
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
我找到了答案,这要归功于@jonsharpe使用Python 3.8的海象运算符的漂亮解决方案:
def answer_as_ul(question, input_prefix='• '):
print(question)
answer_list = list()
while answer := input(input_prefix):
answer_list.append(answer)
return answer_list