[英]My list is empty but I can't figure out why?
我是一个初学者,我正在使用 Python 3 并使用文本文件为学校项目制作各种杂货清单,您可以在其中通过代码选择其中一项。 因此,您选择的项目将 go 放入单独的列表中,稍后应该打印出来。 问题是我的用户可以选择的列表是空的,我真的不知道该怎么做。
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 语句都无法访问。
其次,您将列表传递给listInsert
但您没有对它们做任何事情。 然后,您分配了变量item_code
和quantity
来获取用户输入,这意味着传递给您的 function 的列表的引用消失了。
第三,您似乎在valda_varor
和antalen
中有两个全局列表变量,但它们在其他任何地方都没有使用。 也许您打算改用这些列表,因为用户输入值实际上已附加到这些列表中。
接下来,当您调用listInsert
时,您的返回值不会在任何地方使用。 如果要使用 function 的返回值,则必须将 function 调用分配给变量。
x=listInsert(item_code, quantity) #your return value from the function is assigned to x variable
最后,您的列表是空的,因为您刚刚返回了之前在 function 中创建的空列表。 您没有以任何方式修改列表。
您的代码存在太多问题,无法列出。 我更正了它们以使代码按照我认为您的意图工作。 此代码中存在可以消除的冗余,但我保留它们以复制您试图实现的目标。 几个重要的点:
仔细研究这段代码并从中学习:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.