11/15 Count, Question for the Experts


#1



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

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?


#2

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


#3

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:


#4

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.

str(eggs)

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

#5

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...


#6

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'.


#7

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')


#9