Python 我的列表为空,但我可以';我不明白为什么?
我是一个初学者,正在为一个学校项目制作一个杂货清单,使用Python3,使用一个文本文件,您可以通过代码选择其中一个项目。因此,您选择的项目将进入一个单独的列表,稍后将被打印出来。问题是,我的用户可以选择的列表是空的,我真的不知道该做什么Python 我的列表为空,但我可以';我不明白为什么?,python,python-3.x,Python,Python 3.x,我是一个初学者,正在为一个学校项目制作一个杂货清单,使用Python3,使用一个文本文件,您可以通过代码选择其中一个项目。因此,您选择的项目将进入一个单独的列表,稍后将被打印出来。问题是,我的用户可以选择的列表是空的,我真的不知道该做什么 def listInsert(item_code, quantity): item_code = input("What item do you want? ") while koden != "#"
def listInsert(item_code, quantity):
item_code = input("What item do you want? ")
while koden != "#":
quantity = input("How many do you want? ")
valda_varor.append(item_code)
antalen.append(quantity)
print("The item is in your bag")
koden = input("Do you want anything more, write # if not")
else:
val2 = input("Write # to end")
return item_code
return quantity
def köpa(krävs):
print("Choose your items with the help of your code, write # to end and 1 to continue")
item_code = []
quantity = []
while True:
val2 = input("What do you want to do?")
if val2 == "1":
listInsert(item_code, quantity)
else:
print("bye")
break
return item_code
return quantity
您的代码有一些问题 首先,正如khelwood所解释的,两个函数中的第二个return语句都是不可访问的 第二,您将列表传递到
listinert
,但您没有对它们做任何操作。然后分配变量item\u code
和quantity
以获得用户输入,这意味着传递给函数的列表引用消失
第三,在valda_varor
和antalen
中似乎有两个全局列表变量,但它们在其他任何地方都不会使用。也许您打算使用这些列表,因为用户输入值实际上会附加到这些列表中
接下来,当您调用listInsert
时,您的返回值不会在任何地方使用。如果要使用函数的返回值,必须将函数调用指定给变量
x=listInsert(项目_代码,数量)#函数的返回值被分配给x变量
最后,您的列表是空的,因为您刚刚返回了在函数前面创建的空列表。您没有以任何方式修改列表。您的代码有太多问题无法列出。我更正了它们,以使代码按照我认为您想要的方式工作。这段代码中有可以消除的冗余,但我保留它们是为了复制您试图实现的目标。有几点很重要:
def listInsert():
koden = "y"
valda_varor = []
antalen = []
while koden != "n":
item_code = input("What item do you want? ")
quantity = input("How many do you want? ")
valda_varor.append(item_code)
antalen.append(quantity)
print("The item is in your bag")
koden = input("Do you want anything more? Write y or n: ")
for i in range(len(valda_varor)):
print(f'You bought {antalen[i]} of item {valda_varor[i]}')
def köpa():
print("Choose your items with the help of your code.")
while True:
response = input("Do you want to buy? Write y or n: ")
if response == "y":
listInsert()
else:
print("bye")
break
köpa() #starts running the code
请在每个函数中发布第二条返回语句,因为上一条返回语句将结束函数。您将列表传递到
listinert
,但该函数不传递列表;它只是将变量设置为其他变量。顺便说一句,你不应该在代码中使用äöü,因为其他语言没有这些符号。。。不确定您计划做什么-但是您不会将项目附加到空列表中。。。正如已经指出的,代码中有几个错误