我为什么无法隐式地将浮点数转换为字符串?

2024-05-04 17:52:26 发布

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

运行这个有点麻烦。基本上,我只想得到一个数额,如果它超过50免费送货和少于10美元额外收费。我一直收到一个关于将浮点转换为str隐式的错误?我认为我的输入应该被视为浮动?在

#declare flags
shippingCharge = 10
freeShipping = False
#Get number and convert to float?
purchaseAmount = float(input("\nHow much is the purchase amount? "))

if (purchaseAmount) >= 50 : 
    freeShipping = True
    print("Your purchase amount is " + purchaseAmount + "$ and shipping is free!")
else : 
    print("Your purchase amount is " + purchaseAmount + "$ and shipping is " + shippingCharge + "$.")
    purchaseAmount = shippingCharge + purchaseAmount
    print("Your new total is " + purchaseAmount)
print ("Have a nice day and thank you for shopping with us.")

Tags: andyourisfloatpurchaseamount浮点shipping
3条回答

问题在于你的书面陈述:

print("Your purchase amount is " + purchaseAmount + "$ and shipping is free!")

如果要在不进行转换的情况下连接字符串和浮点,请尝试向变量添加str()强制转换:

即:

^{pr2}$

也可以使用格式:

print("Your purchase amount is {0}$ and shipping is free!".format(purchaseAmount))

因为Python是一种强类型语言:

https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language

您需要显式地将类型转换为string。它不会自动为你故意这么做。在

只需将purchaseAmount替换为str(purchaseAmount),就可以了。在

How much is the purchase amount? 50
Your purchase amount is 50.0$ and shipping is free!
Have a nice day and thank you for shopping with us.

相关问题 更多 >