def getExamPoints(examPoints):
for examPoints in range(1, 5):
examPoints = input("Please enter students exam scores: ")
totalPoints = input("Please enter total possible points: ")
print("The total exam points are: " + sum(int(examPoints)))
avg = float(int(str(examPoints))/int(totalPoints))
print("the average is: ", avg)
在第5行,我得到了错误'int object is not iterable'
,我不知道为什么。
我正在尝试写一个有函数的程序,这个函数的这部分是假设取80分中的4个家庭作业分数,然后计算平均分数,然后取平均值,乘以家庭作业在课堂上的价值百分比,但我甚至不能得到程序的这一块,以获得家庭作业分数的平均值。我不是很擅长python,如果格式不正确,我提前道歉,但如果有任何帮助,将不胜感激。
发布于 2014-02-25 00:54:09
examPoints
不是原始代码中的输入列表,而是用户输入循环的每次迭代都会覆盖的一个变量:
for examPoints in range(1, 5):
examPoints = input("Please enter students exam scores: ")
相反,您希望单独保留每个输入。例如,通过将其附加到列表:
examPoints = []
for _ in range(1,5):
# add input to list after converting it to an integer
examPoints.append(int(input("Please enter students exam scores: ")))
...
输入文本到整数的转换可以在追加时完成(在无法转换的输入后立即向用户返回错误),也可以在执行求和时使用列表理解或map函数完成:
# sum version
sum([int(v) for v in examPoints])
# map version
sum(map(int, examPoints))
发布于 2014-02-25 00:53:00
对不起,(在我看来)你的代码有点乱。相反,请尝试:
def getExamPoints(examPoints):
points = []
for examPoints in range(1, 5):
points = points + [int(input("Please enter students exam scores: "))]
totalPoints = input("Please enter total possible points: ")
print("The total exam points are: " + sum(examPoints))
avg = float(int(str(examPoints))/int(totalPoints))
print("the average is: ", avg)
sum()查找的是一个可迭代的对象,比如一个列表,然后将其中的所有内容相加。由于examPoints被定义为整数,因此它是不可迭代的。相反,创建一个单独的列表,并将输入放在其中。
https://stackoverflow.com/questions/22002335
复制相似问题