有没有办法对未定义的变量进行 while 循环? (我该如何重写,Python)
Is there a way to do a while loop on a variable that's undefined? (How can I rewrite this, Python)
我想做一个 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
并保留功能?
使用下面的代码。我还为更多 Pythonic 代码添加了一些小调整:
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
也许像这样,但差别不大:
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
感谢 @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
我想做一个 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
并保留功能?
使用下面的代码。我还为更多 Pythonic 代码添加了一些小调整:
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
也许像这样,但差别不大:
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
感谢 @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