0

I was experimenting with for loops and lists in Python earlier today, and I'm a bit stuck on this one thing that's probably very simple... Here's my code:

animals = ["hamster","cat","monkey","giraffe","dog"]

print("There are",len(animals),"animals in the list")
print("The animals are:",animals)

s1 = str(input("Input a new animal: "))
s2 = str(input("Input a new animal: "))
s3 = str(input("Input a new animal: "))

animals.append(s1)
animals.append(s2)
animals.append(s3)

print("The list now looks like this:",animals)

animals.sort()
print("This is the list in alphabetical order:")
for item in animals:
    count = count + 1

    print("Animal number",count,"in the list is",item)

The count variable doesn't work for whatever reason, I've tried to search for this problem but can't find anything. It says it's not defined, but if I put a normal number or a string it works perfectly fine. (I am also sick at the moment so I can't think properly, so this might be really simple and I just didn't catch it) Would I have to make a new for loop? Because when I did this:

for item in animal:
    for i in range(1,8):
        print("Animal number",i,"in the list is",item)

It just spits out each item in the list with the numbers 1-7, which is... better, but not what I want.

Pali
  • 1
  • 1
  • 1
  • 2

3 Answers3

5

You need to define count first like:

count = 0

Another better way to achieve what you want is just:

for count, item in enumerate(animals):
    print("Animal number", count + 1, "in the list is", item)
BPL
  • 9,632
  • 9
  • 59
  • 117
3

You need to initialize count before the loop. Otherwise Python does not know what count is, so it cannot evaluate count + 1.

You should do something like

...
count = 0
for item in animals:
    count = count + 1
    ...
jfschaefer
  • 54
  • 2
  • 3
1

You are trying to increment a value you never set:

for item in animals:
    count = count + 1

Python complains about count because the first time you use it in count + 1, count has never been set!

Set it to 0 before the loop:

count = 0
for item in animals:
    count = count + 1
    print("Animal number",count,"in the list is",item)

Now the first time the count + 1 expression is executed, count exists and count can be updated with the 0 + 1 result.

As a more Pythonic alternative, you can use the enumerate() function to include a counter in the loop itself:

for count, item in enumerate(animals):
    print("Animal number",count,"in the list is",item)

See What does enumerate mean?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343