For loop in dictionaries

def fizz_count(x):
  count = 0
  for item in x:
    if item == "fizz":
      count = count + 1
      return count
loot =["fizz","cat","fizz"]
small = fizz_count(loot)
print(small)

it shows answer 1 instead of 2 :frowning: why ?

By default, at the end of a function a function always returns None. If we want to return something else at the end of the function, we can use the return keyword

thus, when a return keyword is reached, the function ends (given return is the last thing a function does)

the return keyword in your function is reached the moment there is a fizz in the list

but loot consist two “fizz” that means function should return 2 value but it is returning 1 value

yes, but your code is written in such a way that the moment the first fizz is found, return keyword is reached which will end your function. (given return is the last thing a function does), to achieve this return will simply break the loop so it can end the function

Sir, can you tell me the solution to this problem.

Do you understand how return is preventing the correct working of your function at the moment?

We need to place return outside the loop, so it doesn’t end the loop prematurely.

Ohh! thank you so much sir, finally I understand my error but if i place return outside the loop it shows SyntaxError: ‘return’ outside function :frowning:

then you placed return outside the function, that is not right. It should be outside/after the loop so the value is returned after the loop is finished, but inside the function

it’s kinda annoying, if I change count into total inside if loop again it shows result 1 why Sir ? anyway thank you sir.

if loop? You mean if condition or for loop?

if the variable is named count or total doesn’t matter

You have made many changes to your code, what code do you have now?

def fizz_count(x):
  count= 0
  for item in x:
    if item == "fizz":
        total = count + 1
  return total
loot =["fizz","cat","fizz"]
small = fizz_count(loot)
print(small)

print result 1 :frowning: instead of 2

count is and will stay zero, so here:

total = count + 1

we do 0 + 1 which is always one, so total will always be one (if there is at least one fizz in the list)

count is never increasing, how is it ever going to count the total number of fizz elements in the list?

Finally, Sir I understand it completely, thank you so much for your valuable time sir.