由于某种原因,没有将任何用户输入附加到空列表中。我不知道我哪里出了问题。这是我有一个更大的问题的一个例子。任何帮助都将不胜感激。谢谢
list = []
print("Who wrote War and Peace?: ")
book1 = input()
for i in list:
list.append(book1)
print(f"Author: " + i)
发布于 2022-09-04 03:18:14
我看到您正在尝试将一个项添加到一个空列表中,并使用for循环来访问它,但是您所做的恰恰相反。
另一件事是,您正在使用格式化字符串来打印作者的姓名。记住,在执行格式化字符串时,使用{},只需将变量放入其中,而不是执行+变量
my_list = []
print("Who wrote War and Peace?: ")
book1 = input('')
my_list.append(book1)
for i in my_list:
print(f"Author: {i}")
发布于 2022-09-04 02:43:36
当您打印出list
的值时,Python会将其解释为list
数据类型。您可以通过将变量名更改为l
或my_list
来解决问题。
编辑:进一步注意,您正在循环列表中的每一项,但是列表是空的,所以for -循环不会运行。
发布于 2022-09-04 02:58:42
欢迎来到StackOverFlow!
从我的复制来看,列表中没有"i“值(空值)。因此,for循环没有触发,也没有什么要循环的。
复制:
user_input=(input("\nWhat is the airspeed velocity of a (European) unladen swallow?: "))
a=False
list = []
for i in list:
a=True #if For Loop is triggered a is True and prints pass
list.append(user_input)
print(list)
if a is not True: #if For loop is not triggered then fail will be printed
print('fail')
else:
print('pass')
结果
What is the airspeed velocity of a (European) unladen swallow?: 24 mph
fail
以便添加到列表中。删除初始输入的for循环。
user_input1=(input("\nWhat is the airspeed velocity of a (European) unladen swallow?: \n"))
list_ = []
list_.append(user_input1)
user_input2=(input("We are the Knights who say?: \n"))
for i in range(len(list_)):
list_.append(user_input2)
print(list_)
结果
What is the airspeed velocity of a (European) unladen swallow?:
24 mph
We are the Knights who say?:
Ni
['24 mph', 'Ni']
正如神经性说的那样,不要用列表作为列表的变量(我通常在末尾加一个"_“)。(详见他们的评论)
干杯!
https://stackoverflow.com/questions/73596435
复制相似问题