Why this code works?


#1

Soo, my 'problem' is this code works properly for codecademy, but when I was checking this in visualizer I got problems.

In visualizer:

  • it works when I check count('lalka', 'l'), it doesn't work
  • when I check count('lalka', 'la') - returns 0, it doesn't work
  • when I check count(7, 7.0) - 'int' isn't iterable.

I understand why it doesn't work in visualizer, but don't get why codecademy says it's ok.

def count(sequence, item):
    n = 0
    for c in sequence:
        if c == item:
            n += 1
        else:
            continue
    return n

#2

Hi @szkaplerny ,

The count function is meant to work with a list and an item as arguments, rather than with two strings. However, it can work with two strings, if the second argument is a single character.

The reason that count('lalka', 'la') returns 0 is that the function checks one character at a time, while 'la' contains two characters. Therefore, 'la' is not recognized.

Codecademy passes your submission, because it tests it for list and item arguments, and for that the function works correctly.

By the way, you do not need ...

else:
    continue

#3

@appylpye - ok, now I get. I was just trying make this task more 'advanced'.
And yea, I don't know why I put continue there...