我有一个问题,我需要采取用户输入即(杰克,10,10,9,10,10)与杰克是学生的名字和数字是考试成绩。我需要找到这些考试成绩的平均值,并打印出学生的名字。这个问题看起来很简单,我得到一个输出错误,它说:
>>> calcMarks()
Enter marks:Jack,10,10,9,10,10
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
calcMarks()
File "xyz", line 12, in calcMarks
avg = sum(list[0:len(list)])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
以下是我目前的代码:
def calcMarks():
#input = Jack,10,10,9,10,10
userInput = input('Enter marks:')
list = userInput.split(',')
name = list.pop(0)
#print(type(list))
#print(type(name))
avg = sum(list)/(len(list)-1)
print(name + ' ' + avg)
avg
是一个数字。为了与其他字符串连接,需要首先将其转换为带有str()
的字符串此外,您正在对字符串求和,在求和之前需要将其转换为数字。你知道吗
这种方法的问题是,当从
input
读取数据时,总是会得到一个字符串,因此必须将标记转换为整数来计算平均值。我会这样做:相关问题 更多 >
编程相关推荐