Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用循环和列表_Python 3.x - Fatal编程技术网

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)