Python 3.x 使用循环和列表
想要向用户请求一个字符串并将其添加到列表中等等,只要该字符串不是空的,为什么它会创建一个无休止的循环?如果您希望用户将输入值添加到列表中,直到他输入一个空字符串为止。这可能对你有帮助Python 3.x 使用循环和列表,python-3.x,Python 3.x,想要向用户请求一个字符串并将其添加到列表中等等,只要该字符串不是空的,为什么它会创建一个无休止的循环?如果您希望用户将输入值添加到列表中,直到他输入一个空字符串为止。这可能对你有帮助 def input_list(): first_list = [] string_requested = input() while string_requested != [""]: new_list = first_list.append(string_requested
def input_list():
first_list = []
string_requested = input()
while string_requested != [""]:
new_list = first_list.append(string_requested)
产出:
def input_list():
first_list = []
string_requested = input("enter string")
first_list.append(string_requested)
while len(string_requested) != 0:
string_requested = input("enter string")
if len(string_requested) != 0:
first_list.append(string_requested)
print(first_list)
input_list()
您必须读取循环中的输入,才能用新输入填充列表。另外,正如已经指出的,append
返回None
,不应赋值。更不用说,你从来没有使用过new\u list
。以下工作将起作用:
enter string: One
enter string: Two
enter string: Three
enter string: FOur
enter string:
['One', 'Two', 'Three', 'FOur']
要向用户请求一个字符串并将其添加到列表中,等等,只要该字符串不是空的,为什么它会创建一个无休止的循环?在循环中不接受新的输入。还要注意的是,新列表从未实际使用过(而且没有,append不会返回任何内容)。非常感谢您的完整解释@维尼思说!接受其中一个答案,将其标记为已解决。
def input_list():
new_list = []
while True:
string_requested = input()
if string_requested == "":
return new_list
new_list.append(string_requested)