python - 类型错误 : cannot concatenate 'str' and 'float' objects on line 10

标签 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: cannot concatenate 'str' and 'float' objects

我还有很多要写,我卡在了这一行 print(student.capitalize() + "获得平均考试成绩 "+ ((averageTest)/3))

最佳答案

您不能添加字符串和数字(​​ float )。相反,在将它与另一个字符串添加之前,将您的 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)

关于python - 类型错误 : cannot concatenate 'str' and 'float' objects on line 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46569036/

相关文章:

python - 无法理解这条 python

python - 使用 self.sender() 检查 PyQt QPushButton 是否被检查

python - 使用 os.scandir 进行文件夹搜索

python - 传递带有多个参数的字符串

c# - 为什么这个相机不能连续偏航?

python - 在 APScheduler 中超出计划的手 Action 业执行

python-3.x - 如何在 selenium python 中按回车键?

algorithm - 为什么 "="用于表示算法的时间复杂度而不是 "∈"?

计算量大的程序的性能测试

python - 如何使用 Google App Engine Python 将变量从 app.yaml 传递到 main.py