Count


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>

```python

def count(sequence,item):

found=0
for i in sequence:
if i==item:
found=found+1
return found
else:
return 0
Oops, try again. Your function fails on count([4, ‘foo’, 5, ‘foo’],5). It returns 0 when it should return 1.

<do not remove the three backticks above>

#2

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/1?curriculum_id=4f89dab3d788890003000096#


#3

Hey! First of all, I highly recommend you to format your text when using code to make it more clear.

So, this is your original code with my comments:

def count(sequence,item):
    found = 0
    for i in sequence: #so far the code is working fine, the problem starts from this point
        if i == item:
            found = found + 1 #OK, this is correct
            return found #Prob1: this return is inside the for and if when it should be the return of the function as a whole (check my corrected code below)
        else: #Prob2: by using else, when i is not found in item, it will return 0, and that is not what we want
            return 0

This is the corrected code:

def count(sequence,item):
    found = 0
    for i in sequence:
        if i == item:
            found = found + 1
    return found #the return is out of the for loop and makes part of the function (check indentation) and I also removed the else, as there is no need for it 

#4

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