首页 > 解决方案 > 使用循环和列表

问题描述

def input_list():
    first_list = []
    string_requested = input()
    while string_requested != [""]:
        new_list = first_list.append(string_requested)

想向用户询问一个字符串并添加到列表中等等,只要字符串不为空,为什么会创建一个无限循环?

标签: python-3.x

解决方案


您必须读取循环的输入才能用新输入填充列表。此外,正如已经指出的那样,append返回None并且不应分配。new_list更不用说,无论如何你永远不会使用。以下将起作用:

def input_list():
    new_list = []
    while True:
        string_requested = input()
        if string_requested == "":
            return new_list
        new_list.append(string_requested)

推荐阅读