Why does my fizz_count return 1 instead of the correct answer?


#1

Question

Why does my fizz_count return 1 instead of the correct answer?

Answer

Assuming the rest of your code is correct, the issue here is that your function returns too soon. If you put your return statement inside of your for loop, it can only possibly run one time.
Remember, a function exits immediately when it executes a return statement and returns whatever value is there. Take a look at the code snippets below:

total = 0
for item in my_list:
  if item == 2:
    total += 1
  return total  # return is indented to be inside of the for loop!

To fix this, return should be written on the same indentation level as the for loop so that it doesn’t execute it until the loop is done looping, like this:

total = 0
for item in my_list:
  if item == 2:
    total += 1
return total  # doesn’t return until AFTER the loop

FAQ: Learn Python: A Day at the Supermarket - Lists + Functions