今天早些时候,我在Python中尝试了for循环和列表,我有点纠结于这一点,这一点可能非常简单。。。这是我的代码:
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)
不管是什么原因,count变量都不起作用,我试图搜索这个问题,但是什么也找不到。它说它没有定义,但如果我把一个正常的数字或字符串,它工作得很好。(我现在也病了,所以我不能正确地思考,所以这可能真的很简单,我只是没有抓住它)我需要做一个新的for循环吗?因为当我这么做的时候:
for item in animal:
for i in range(1,8):
print("Animal number",i,"in the list is",item)
它只是把列表中的每一项都用数字1-7表示出来,也就是。。。更好,但不是我想要的。
您需要在循环之前初始化
count
。 否则Python不知道count
是什么,因此它无法计算count + 1
。你应该做些
首先需要定义count,如下所示:
另一个更好的方法是:
您试图增加从未设置的值:
Python抱怨
count
,因为第一次在count + 1
中使用它时,count
从未设置!在循环之前将其设置为
0
:现在,第一次执行
count + 1
表达式时,count
存在,并且可以用0 + 1
结果更新count
。作为一个更具python风格的替代方案,您可以使用^{} function 在循环本身中包含一个计数器:
见What does enumerate mean?
相关问题 更多 >
编程相关推荐