的Python项目在计数循环

问题描述:

我是用Python中的for循环和试验名单今天早些时候,我有点停留在这一件事情,可能是很简单的......这里是我的代码:的Python项目在计数循环

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) 

计数变量不管用什么原因,我试图寻找这个问题,但找不到任何东西。它说它没有定义,但如果我把一个正常的数字或字符串它工作得很好。 (我现在还不舒服,所以我想不出来,所以这可能很简单,我只是没有抓住它)我需要做一个新的循环?因为当我这样做时:

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

它只是吐出列表中的每个项目与数字1-7,这是...更好,但不是我想要的。

+0

你忘了定义'count'。在for循环之前添加'count = 0'。 – ozgur

您需要定义数第一,如:

count = 0 

另一种更好的方式来实现你想要的仅仅是:

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

您正在试图增加你从来没有设置一个值:

for item in animals: 
    count = count + 1 

Python抱怨count,因为你第一次使用它在count + 1count从未设置!

其设为0循环之前:

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

现在执行count + 1表达首次count存在并且count可以与0 + 1结果被更新。

作为一个更Python的替代,可以使用enumerate() function包括在循环本身的计数器:

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

What does enumerate mean?

您需要在循环之前进行初始化count。 否则Python不知道count是什么,所以它不能评估count + 1

你应该这样做

... 
count = 0 
for item in animals: 
    count = count + 1 
    ...