我可以缩短这个吗?没有百分比的IE =被使用两次?

时间:2015-10-13 19:42:09

标签: python-3.4

percentage = int(input("\nWhat percentage of your bill would you like to calculate? "))
percentage = float(round(percentage / 100 * bill, 2))

大家好

Python新手并想知道上面两行代码是否可以缩短为仅包含'percentage ='一次?

由于'百分比'变量是由用户输入定义的,我假设在完成之前我不能将'百分比'定义为​​等式,因此两个独立的代码行?

如果它有助于理解最终目标,那么这里是整个代码 - 它是一个简单的小费计算器:

# Tip calculator
# calculates a %15 and %20 tip for any given meal
# code by c07vus


print("\nHello, welcome to tip calculator!")

bill = float(input("\nIn £'s what was the bill total? "))

fifteen = float(round(15 / 100 * bill, 2))

twenty = float(round(20 / 100 * bill, 2))

print("\nA %15 tip of your bill would be:", fifteen, "pounds")
print("\nA %20 tip of your bill would be:", twenty, "pounds")

print("\nYou can also calculate any percentage you like!")

percentage = int(input("\nWhat percentage of your bill would you like to calculate? "))
percentage = float(round(percentage / 100 * bill, 2))

print("\nThank you, your tip would be:", percentage, "pounds")

input("\n\nPress the enter key to exit")

感谢所有的帮助和建议!

1 个答案:

答案 0 :(得分:1)

当然可以将它放在一行中:只需将分配给percentage的表达式放到第二行中使用该值的位置即可。但是不要指望这条线很漂亮或可读......

percentage = float(round(int(input("\nWhat percentage of your bill would you like to calculate? ")) / 100 * bill, 2))

一般来说,我会坚持你现在的版本。但是,在这种特殊情况下,我会重命名第二个变量,因为这不再是百分比!这是小费。

percentage = int(input("\nWhat percentage of your bill would you like to calculate? "))
tip = float(round(percentage / 100 * bill, 2))

另外,你做了三次计算!这应该足以让这个功能成为一个功能:

to_tip = lambda percent: float(round(percent / 100 * bill, 2))
... # use that same function to calculate fifteen and twenty
tip = to_tip(percentage)

最后,如果要将结果显示为完全两个小数位,则使用格式字符串优于舍入。

print("\nThank you, your tip would be: {:.2f} pounds".format(tip))