格式化计算变量时出现“ValueError:无效的格式说明符”

2024-05-13 01:25:19 发布

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

这是我第三次和python一起工作了,因为我在学习Gaddis的教科书,所以我不得不为烘焙饼干制作一个配料调整程序。但是,我尝试格式化数字的最后一行代码ValueError:Invalid format specifier在我尝试运行时出现。在

在这里读了一些与我相似的问题,但是我发现这些程序的实例要理解和联系到我的问题要复杂得多。在

#The recipe produces 48 cookies with this amount of the ingredients.
#Write a program that asks the user how many cookies he or she wants to make,
#then displays the number of cups of each ingredient needed for the specified
#number of cookies.

#1.5 cups of sugar
#1 cup of butter
#2.75 cups of flour

default_batch = 48
defaultCups_Sugar = 1.5
defaultCups_Butter = 1
defaultCups_Flour = 2.75

num_cookies = float(input("How many cookies would you like to make? "))

calCups_Sugar = (num_cookies/default_batch)*defaultCups_Sugar
calCups_Butter = (num_cookies/default_batch)*defaultCups_Butter
calCups_Flour = (num_cookies/default_batch)*defaultCups_Flour

print ("It would take the following amount of ingredients to       make", \
   num_cookies, "cookies:")

print ("Cups of Sugar:", format(calCups_Sugar, ";.2f"))
print ("Cups of Butter:", format(calCups_Butter, ";.2f"))
print ("Cups of Flour:", format(calCups_Flour, ";.2f"))

我希望输出最多只保留两位小数,但是当我运行它时,会出现ValueError:Invalid format specifier错误消息。在


Tags: ofthetoformatdefaultmakebatchsugar
1条回答
网友
1楼 · 发布于 2024-05-13 01:25:19

Python中的格式说明符不包含分号。将字符串格式化为两位小数的正确语法是format(number, ".2f"),而不是{}

相关问题 更多 >