Supermarket 4


#1

Afternoon Fellow Coders due to being busy I haven't been able to code so I am going to redo super market all over again and having some trouble with this code:

# Write your function below!
def fizz_count(x):
    count = 0
    for item in x:
        if item == 'fizz':
            count += 1
    print count
x = ["fizz","cat","fizz"]
fizz_count(x)

It says the answer is 1 instead of 2 which is the real answer so I don't know please help me out! Thanks for all the help in advance!


#2

Change print to return, and then print the return value.

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

#3

I tried that earlier and it didn't work


#4

Show us your code, again, please.


#5

# Write your function below!
def fizz_count(x):
    count = 0
    for item in x:
        if item == 'fizz':
            count += 1
            return count
x = ["fizz","cat","fizz"]
fizz_count(x)

#6

Remove the indentation so it lines up with the for.


#7

It worked but I want to know why so I know for future reference


#8

When the return was in the if code block, count only reached 1 and then returned.

If the return is in the loop code block then it returns after only one iteration.

Moving the return to the left edge of the function code block it is outside of any nested blocks and returns only after everything else is finshed executing.


#9

OK Thank you so much! You seem to be that go to guy! Have a nice day!


#10

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