Python3课程,在print语句结尾的句点之前有额外的空间问题

2024-09-27 07:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python简介课程,所以这些内容仍然是相当基本的,但是如果有任何帮助,我们将不胜感激

我尝试过多种方法,我知道print语句中的逗号会自动添加空格,但我无法添加加号和句点而不出现错误

这是我的密码:

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退出


Tags: the方法ismypointavgprintaverage
3条回答

试试这个:

print('After the {} point bonus, my average is {}.'.format(rounded_bonus, rounded_avg))

在Python3中,引入了F字符串以使这段代码更简单。见下文:

rounded_bonus = 0.5

rounded_avg = 87.6

print(f'After the {rounded_bonus} point bonus, my average is {rounded_avg}.')

以下是了解更多信息的链接:https://realpython.com/python-f-strings/

使用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)

相关问题 更多 >

    热门问题