11. Count


#1

def count(sequence, item):
found = 0
for num in sequence:
if num == item:
found += 1
else:
return found
i am unable to do this


#2

Hi, @karray ,

Be sure to format code any time you post it, so we can see important details that may not be visible if it were unformatted. See How do I format code in my posts?.

We cannot see the indentation of your code, since it is not formatted, and in this case, the indentation may relate to the problem you are having.

Does your function always return the value of found after it has completed the counting process?


#3
def count(sequence, item):
    found = 0
    for num in sequence:
        if num == item:
            found += 1
        else:
            return found

#4

We still cannot see the indentation. However, you should check whether your else block is indented to match the for loop header or the if block header. One of these will give the desired result, and the other will not. Consider which one will work, and then try it out.

EDIT (November 19, 2016):
Thanks for the formatting. Your else matches the if. Therefore, the function will terminate and return a result the very first time that num does not match item.


#5

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