我正在学习 python 入门类(class),所以这些东西仍然是相当基础的,但我们将不胜感激任何帮助。
我试过很多东西,我知道打印语句中的逗号会自动添加一个空格,但我无法添加加号和句点而不会出错
这是我的代码:
bonus = survey_completers / class_size
avg = my_current_average + bonus
rounded_bonus = round(bonus, 1)
rounded_avg = round(avg, 1)
textOne = str("After the")
textTwo = str("point bonus, my average is")
textThree = str(".")
print(textOne, rounded_bonus, textTwo, rounded_avg, textThree)
给出输出:
After the 0.5 point bonus, my average is 87.6 .
当预期输出是句号紧跟在 87.6 后面的句子时
我试过如下:
bonus = survey_completers / class_size
avg = my_current_average + bonus
rounded_bonus = round(bonus, 1)
rounded_avg = round(avg, 1)
textOne = str("After the")
textTwo = str("point bonus, my average is")
print(textOne, rounded_bonus, textTwo, rounded_avg + ".")
这给了我这个错误:
Traceback (most recent call last):
File "CIOSBonus.py", line 40, in <module>
print(textOne, rounded_bonus, textTwo, rounded_avg + ".")
TypeError: unsupported operand type(s) for +: 'float' and 'str'
命令以非零状态 1 退出
最佳答案
使用 f-strings :
bonus = survey_completers / class_size
avg = my_current_average + bonus
rounded_bonus = round(bonus, 1)
rounded_avg = round(avg, 1)
result = f"After the {rounded_bonus} point bonus, my average is {rounded_avg}."
print(result)
关于Python 3 类(class),在打印语句末尾的句点之前有额外空间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66322684/