4. Lists and Functions



This is my code.
def fizz_count(x):
count = 0
for string in x:
if string=="fizz":
count= count+1
return count

It is returning 1 every time there is any occurrence of the string "fizz". I need it to add 1 to count for every occurrence of the string "fizz" and then return that number. Any suggestions on how best to do this?

Replace this line with your code.


Indentation is very important in python. The way you've copied your code, we can't see those indents. Since your code looks great, I'm thinking you have an indentation problem. Make sure you only return count when you're sure all the function's work has been done -- that is, outside of any if or for loop.

(I wrote this post based on the assumption your code looks like below)

def fizz_count(x):
  count = 0
  for string in x:
    if string == "fizz":
      count = count + 1
      return count


Your code is correct. You just have to call the function with arguement "fizz"
For example-

print fizz_count(["fizz","buzz","fizz"])

It will return - 2


Thanks. My code is indented like the code above. It still gives me this error message however.

Oops, try again. fizz_count(['buzz', 'fizz', 1, 10, 'fizz', 'fizz', 4, 'fizz']) returned 1 instead of the correct answer: 4


Unfortunately, in that situation my code is returning 1.


The code I showed has incorrect indentation. The position of return makes sure that the function will end at the first time it finds "fizz" because it's inside the if statement. If you were to un-indent one level (move it left), it would be inside the for loop and end the function as soon as the for loop runs the first time. If you un-indent it two levels, it will end the function after the for loop has finished. If you un-indent it 3 levels (up against the left edge of the editor with no whitespace), it will be outside the function and throw an error.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.