【问题标题】:TypeError: cannot concatenate 'str' and 'float' objects on line 10 [duplicate]TypeError:无法在第 10 行连接“str”和“float”对象 [重复]
【发布时间】:2017-10-04 15:46:23
【问题描述】:
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))

【问题讨论】:

标签: python python-3.x math


【解决方案1】:

您不能添加字符串和数字(​​浮点数)。相反,将浮点数转换为字符串,然后再添加另一个字符串。你可以这样做

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)

【讨论】:

  • 谢谢!!还有什么我应该做的吗?这是一个让老师选择每篇研究论文/课堂参与/期末考试的权重的项目。它必须是用户友好的......有什么建议吗?谢谢
  • 除此之外,我还建议为“平均测试”之类的东西创建函数,该函数返回平均值,而不必稍后再除。这将为您在添加额外参数(例如每个测试的权重)时提供更大的灵活性,并允许您以稍微更有条理的方式进行编码,因为它鼓励根据您希望代码执行的操作在“块”中进行思考。例如 - 定义测试和加权、要求输入(姓名和测试结果)、计算加权结果、根据加权结果计算字母等级。
  • 谢谢!!我真的很感激它,从昨天开始它已经走了很长一段路......
  • 没问题!不要忘记将答案标记为已接受,祝您项目顺利完成!
  • 如何让它被接受?
猜你喜欢
  • 1970-01-01
  • 2017-10-13
  • 2017-05-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多