gpt4 book ai didi

python - :TypeError: argument of type 'function' is not iterable", 但在单独测试时有效

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:02 31 4
gpt4 key购买 nike

我是 Python 2 的新手。我正在尝试构建一个“购物车”Python 程序,但卡在了“放入购物车前检查库存”步骤。

首先,我在这里阅读了很多相同问题的线程,但它们似乎与我的原因不同。

其次,我已经将每个函数和测试分开放在不同的文件中。他们单独工作得很好。但是当加入 check_stock(y) 函数时,它给出了错误。

我认为问题出在“in”命令上。

    def check_stock(y):             #// Problem in this function // 
if y in list:
print "%s is available" % y
add_to_cart(y)
else:
print "Sorry, but %s is not available." % y

def check_finish():
y = raw_input(">")
if y == "checkcart":
print cart #check inside shopping cart
elif y == " ":
check_finish() #loop back for blank
elif y == "list":
list() #present the list
else:
while y != "ok": #"ok" = finished shopping
check_stock(y)
else:
print "Checking out..."
sorted(cart)
print "Your item(s) are %s." % cart
exit(0)

下面是剩余的代码,如果有帮助的话:

cart = []
list = ['apple', 'banana', 'cat', 'dog', 'elephant', 'flamingo', 'goofy', 'ham']
a = 0

def list():
print list #present the list
def representInt(s): #check if value is integer
try:
int(s)
return True
except ValueError:
return False
def annoyedAtError(a): #interaction for repeated mistakes
if a < 2:
print "Numbers only please"
elif 2 < a < 4:
print "Man, just do as I say, please. I have another shift tonight."
elif a == 5 :
print "Hey, seriously?"
else:
print "..."
def check_stock(y): #// PROBLEM HERE // cross-check with list if item is available
if y in list:
print "%s is available" % y
add_to_cart(y)
else:
print "Sorry, but %s is not available." % y

def add_to_cart(y):
amount = (raw_input("How many do you want to add? > "))
if representInt(amount) == False:
annoyedAtError(a)
global a
a = a + 1
add_to_cart(y)
else:
y = y + " " + amount
print "%s is added to cart" % (y)
cart.append(y)
check_finish()
def check_finish():
y = raw_input(">")
if y == "checkcart":
print cart #check inside shopping cart
elif y == " ":
check_finish() #loop back for blank
elif y == "list":
list() #present the list
else:
while y != "ok": #"ok" = finished shopping
check_stock(y)
else:
print "Checking out..."
sorted(cart)
print "Your item(s) are %s." % cart
exit(0)
def welcome():
print """\nWelcome to cyber shopping.\n
Please enter things you want to buy.
Check your cart by typing: checkcart
type "ok" when finished.
type "list" for things available for buying"""
def start():
welcome()
check_finish()

start()

最佳答案

您创建了一个名为 list 的列表(您不应该这样做,因为它已经是内置名称),但是您还创建了一个名为 list 的函数(再次强调,不要这样做)。 list 现在指的是函数,而不是你的列表。因此,当您检查 y in list 时,它会尝试检查该项目是否在函数中。您不能在函数上使用 in,因此会出现错误。解决方案很简单:为事物使用更清晰的名称!!

关于python - :TypeError: argument of type 'function' is not iterable", 但在单独测试时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210393/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com