11/15 Count, Question for the Experts



I am trying to use the str built in function. I get this error:

Traceback (most recent call last):
  File "python", line 12, in <module>
NameError: name 'eggs' is not defined

I was under the idea that str(item) would turn any variable into a string. This would allow any variable added to 'Sequence' and 'Item' to be turned into strings so I can compare them together.

The idea behind it is that the CodeAcademy states:'
'3. The item you input may be an integer, string, float, or even another list!

def count(sequence, item):
    total = 0
    t = str(item)
    m = str(sequence)
    for x in m:
        print 'test 1' #This is a test to check loop
        if t in x:
            print ' test 2' #This is a test to check loop
            total += 1
    return total
print count(['bacon', 'eggs', 'cheese', 'eggs'],eggs)

Any tips or insight?


Did you mean to write this in quotes, "eggs"?


No, this is what the program throws at you when you click submit:

    Oops, try again.
    Your function fails on count(['bacon', 'eggs', 'cheese', 'eggs'],eggs). It returns 0 when it should return 2.

Here is a screencap:


The error you are seeing is reproducable but it makes little sense, given a name that is not defined. We cannot convert a NAME to a string, only the value it may refer to.


will not give us, 'eggs'. If it's value is say 3.14, the above will give, '3.14'

We also would not want to convert a list (sequence) to a string. We shouldn't be converting anything, by rights, since some sequences may be of strings, and others may be of numbers, and still others may even be lists.

So if we simplify your code, we arrive at,

def count(sequence, item):
    total = 0
    for x in sequence:
        if x == item:
            total += 1
    return total


I tried that line already but same error:

I think its an error in the program more than a user one. My code, while definitely not optimized like yours, worked on everything I inputted except this one line

Actually I figured out why it counted it wrong. It would not let me print it to test the code. That is the only time it produced the error...


No, this doesn't run because of a typing error in the last line. You have written:

print count(['bacon', 'eggs', 'cheese', 'eggs'],eggs)

What you should have written is :

print count(['bacon', 'eggs', 'cheese', 'eggs'], 'eggs')

Notice the quotation marks around that final 'eggs'.


There you go,

def count(sequence, item):
total = 0
for x in sequence:
if item == x:
total += 1
return total

print count(['bacon', 'eggs', 'cheese', 'eggs'],'eggs')