Exercise 4: Lists + Functions


#1



https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/0/4?curriculum_id=4f89dab3d788890003000096

Error Message reads: Oops, try again. fizz_count(['fizz', 1, 'buzz', 4, 3, 'fuzz', 'fuzz', 'fizz']) returned 1 instead of the correct answer: 2

It seems like for any number of the instances of 'fizz', the code will return 1 because it counts all instances as only one.


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


#2

@tpsabres,
-1 In Python you indicate a code-block by indentation-level....
-2 A return statement will return the Result but also EXIT's the function....

As you want the return statement to be executed
AFTER the FOR-IN loop has ran through
you will want to place the return statement on the same indentation-level as the FOR-IN loop
therewith indicating the =end= of the FOR-IN loop
like

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

#3

Thank you!

This was driving me crazy.


#4

Thanks for the reply, it was really helpful :slight_smile:

Just wanted to double check again: so if you indented it like tpsabres did at first, will you get rows of 1 printed to the console, or just a single 1? Is it because the whole function is terminated once the return statement is executed, regardless of whether all the items in the list have been ran through yet?

Thanks again :slight_smile:


#5

@umopapsidn

this assumption is =true=....

https://docs.python.org/2.0/ref/return.html


#6

i did it but its not work


#7

copied this exactly and it doesn't work


#8

@desmondgfedaykin
The indentation of your return statement is wrong......
You should be aware that as soon as the return statement is executed
the functon will immediately be EXITED and therefor the FOR-loop is broken...!!


#9

Thanks a bunch, I thought i would never pass that level!!:laughing:


#10

I take back what i said! really.:neutral_face:


#11

Thank you so much!
I was having the same problem!


#12

I just figured out using that same code that all you have to do is move the return count back one block.


#13

You dont really have to use count for this exercise. I used total instead out of habit.And fizz instead of item in this case.

# Write your function below!
def fizz_count(x):
    total = 0
    for fizz in x:
        if fizz == 'fizz':
          total += 1
    return total
    

g = ['a','fizz','e','fizz','fizz']

print fizz_count(g)

#15