我试图编写一个函数,它使用len来查找一个列表的长度,这个列表是python中对象的一个属性。在
我的代码是:
class Supplement(object):
def __init__(self, name, price, ingredients, certifications):
self.name = name
self.price = price
self.ingredients = ingredients
self.certifications = certifications
def print_certifications(self):
print "The supplement %s has the following certifications:" % self.name
for certification in self.certifications:
if len(self.certifications) == 0:
print "Sorry, no certifications for this product."
else:
print certification
UltimateProtein = Supplement("Ultimate Protein", 29.99, ["wheatgrass", "alfalfa grass",
"probiotics"], ["organic", "vegan", "raw"])
UltimateFatLoss = Supplement("Ultimate Fat Loss", 39.99, ["lecithin", "chlorella", "spirulina"],
[] )
UltimateProtein.print_certifications()
UltimateFatLoss.print_certifications()
当我执行程序时,我得到以下输出:
^{pr2}$我希望最后一行是这样写的:
^{3}$是什么阻止我的代码正确使用for循环?在
因为没有对空列表执行
for
循环体。(空列表;没有可迭代的内容)检查
for
循环之外的长度。在相关问题 更多 >
编程相关推荐