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

时间:2019-09-16 22:26:34

标签: python

仅第三次使用python,并且由于Im紧随Gaddis教科书之后,我必须编写一个用于烘烤cookie的成分调整程序。但是,当我尝试运行数字的最后一行代码时,出现ValueError:无效的格式说明符。

在这里阅读一些类似于我的问题,但是我发现这些程序的实例要理解并与我联系起来要复杂得多。

#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 error消息。

1 个答案:

答案 0 :(得分:1)

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