TypeError:无法在第10行连接'str'和'float'对象

时间:2017-10-04 15:46:23

标签: python python-3.x math

print("\n\nThis is a basic program to find the letter grade for a student.")
student = input("What is the students name? : ")
test1 = input("What is the first test grade " + student.capitalize() + " recieved? : ")
test2 = input("What is the second test grade " + student.capitalize() + " recieved? : ")
test3 = input("What is the third test grade " + student.capitalize() + " recieved? : ")
averageTest = (int(test1) + int(test2) + int(test3))
print(student.capitalize() + " recieved an average test grade of " + ((averageTest) / 3))

我正在编写一个基本的成绩计算器程序,无法解决这个问题

  

TypeError:无法连接'str'和'float'对象

我还有更多要写的东西,我坚持这一行 print(student.capitalize() + " recieved an average test grade of " + ((averageTest) / 3))

1 个答案:

答案 0 :(得分:4)

您无法添加字符串和数字(​​浮点数)。而是在将float添加到另一个字符串之前将其转换为字符串。您可以使用

执行此操作
str(x)

在您的情况下,这将是:

# converting the float to a string
print(student.capitalize() + " recieved an average test grade of " + str((averageTest) / 3))

# or, to avoid using addition or conversion at all in a console print
print student.capitalise(), "recieved an average test grade of", averageTest/3

# or even using string formatting (example is py2.7)
print '%s recieved an average test grade of %s' % (student.capitalise(), averageTest/3)