我可以说这个问题已经得到了某种程度的解决,但我找不到解决办法。 问题是,我正在尝试将变量“price”更改为str,并将其格式化为有2个小数位。 代码如下:
def fin():
while True:
global price
wantdrink = input("Would you like a drink? (We only server Coke): ")
if wantdrink not in "Yes" "yes" "No" "no" "Yeah" "yeah" "Nah" "nah":
wrong()
elif wantdrink in "Yes" "yes" "Yeah" "yeah":
print("Got to stay hydrated!")
price = price + 0.50
price = str(price)
"{0:.2f}".format(price)
print("Your order is complete! The total price is", price , "pounds")
time.sleep(3)
print("Your order numbmer is:", num1 + num2 + num3 + num4 + num5)
time.sleep(3)
print("Your food will be delivered in", timnum1 + timnum2, "minuites!")
time.sleep(3)
print("Thanks for ordering from Hungry Horse(TM)!")
time.sleep(3)
sys.exit()
elif wantdrink in "No" "no" "Nah" "nah":
print("Don't get too thirsty!")
price = str(price)
"{0:.2f}".format(price)
print("Your order is complete! The total price is", price, "pounds")
time.sleep(3)
print("Your order numbmer is:", num1 + num2 + num3 + num4 + num5)
time.sleep(3)
print("Your food will be delivered in", timnum1 + timnum2, "minuites!")
time.sleep(3)
print("Thanks for ordering from Hungry Horse(TM)!")
time.sleep(3)
sys.exit()
这只是程序的一部分,展示完整的东西会有帮助吗?你知道吗
无论如何,在运行程序时,python只显示:
ValueError: Unknown format code 'f' for object of type 'str'
有办法解决这个问题吗?我只是在装傻吗?请帮忙。。。你知道吗
您正在使用
str
预转换为字符串。format
已经帮你做了。重新调整空间只是
当然,不能打印具有两位浮点精度的字符串。你知道吗
问题是你没有号码。你已经有一个字符串了。你知道吗
演示:
仔细检查您的代码后:
您将数字转换为字符串,但未指定任何格式:
str(price)
。然后您尝试格式化一个字符串,但没有对返回值执行任何操作。你知道吗要修复它:
顺便说一句,使用浮点数据来计算价格是非常糟糕的做法。如果您想要精确的货币处理,您需要使用十进制或定点类型。原因是碱基-2和碱基-10的分数并不完全一致。这一点在网上有很好的记录和解释。你知道吗
根据疯狂物理学家的答案,您可以将格式化后的价格带入订单完成的行中:
相关问题 更多 >
编程相关推荐