“Two-for”价格的公式比两件商品的总价格低20%。提示用户输入每个值并计算结果

时间:2016-09-02 22:04:38

标签: python

以下是输出的样子:

输入价格1:10.0

输入价格2:20.0

'两个'的价格是24.0美元

我输入的代码是:

price_one = float(input('Enter price 1: '))

print(price_one)

price_two = float(input('Enter price 2: '))

print(price_two)

two_for_price = (price_one + price_two)-((price_one + price_two)*(20/100))

print("The 'two-for' price is $",two_for_price) 

(输入分别为10.0和20.0。)

但我得到的输出是:

Enter price 1: 10.0

Enter price 2: 20.0

The 'two-for' price is $ 24.0

在我需要的最后一行:

The 'two-for' price is $24.0

请帮帮我!!

2 个答案:

答案 0 :(得分:3)

如果我正确读取此内容,您只需要从输出中删除空格。

将您的最后一行更改为:

print("The 'two-for' price is ${0}".format(two_for_price))

答案 1 :(得分:1)

您的根本问题是,在给定项目列表的情况下,print函数行为是打印每个项目,以空格分隔。这对于快速和脏打印来说通常很方便,但是你想要更精致的东西。

您需要做的是创建一个具有适当间距的字符串,然后打印出该字符串。

所以你可以这样做:

print("The 'two-for' price is $" + str(two_for_price) + ".")

问题是(a)那种笨拙和难以理解的问题;(b)它没有正确格式化,它是“2.6美元”而不是“2.60美元”。

您可以使用Python提供的两种格式化机制,可以是显式的,如下所示:

print("The 'two-for' price is ${0}".format(two_for_price))

或隐含,像这样

print("The 'two-for' price is $%f" % two_for_price)

它们看起来好一点,但格式错误分别相同和更差(“$ 2.600000”!)。幸运的是,两者都提供了很好的可自定义格式:

print("The 'two-for' price is ${0:.2f}".format(two_for_price))

print("The 'two-for' price is $%0.2f" % two_for_price)

两者看起来都相当干净,显示效果很好。