我正在尝试使用 codeacademy 来学习 python。作业是“编写一个名为 fizz_count 的函数,它将列表 x 作为输入并返回该列表中字符串“fizz”的计数。”
# Write your function below!
def fizz_count(input):
x = [input]
count = 0
if x =="fizz":
count = count + 1
return count
我认为 if 循环上面的代码很好,因为错误消息(“你的函数在 fizz_count([u'fizz', 0, 0]) 上失败;它应该返回 1 时返回 None。”)只出现当我添加该代码时。
我还尝试创建一个新变量 (new_count) 并将其设置为 count + 1 但这给了我相同的错误消息
非常感谢你的帮助
请您参考如下方法:
问题是你没有循环。
# Write your function below!
def fizz_count(input):
count = 0
for x in input: # you need to iterate through the input list
if x =="fizz":
count = count + 1
return count
还有一种更简洁的方法是使用.count()函数:
def fizz_count(input):
return input.count("fizz")
