如何在Python中将输入数字转换为百分数

6
print ("How much does your meal cost")

meal = 0
tip = 0
tax = 0.0675

action = input( "Type amount of meal ")

if action.isdigit():
    meal = (action)
    print (meal)

tips = input(" type the perentage of tip you want to give ")


if tips.isdigit():
    tip = tips 
    print(tip)

我已经写好了,但不知道如何获取。
print(tip)

当有人输入数字时,它需要显示为百分比。


1
一个百分比就是数字/100 - Adam Smith
这个回答解决了你的问题吗?如何在Python中打印百分比值? - Georgy
4个回答

22
>>> "{:.1%}".format(0.88)
'88.0%'

2

根据你使用input()而非raw_input(),我猜测你在使用python3

你只需要将用户输入转换为浮点数,再除以100即可。

print ("How much does your meal cost")

meal = 0
tip = 0
tax = 0.0675

action = input( "Type amount of meal ")

if action.isdigit():
    meal = float(action)

tips = input(" type the perentage of tip you want to give ")

if tips.isdigit():
    tip = float(tips)  / 100 * meal
    print(tip)

@PadraicCunningham,您是正确的,转换为int也可以工作,但是假设用户决定给出15.5%的小费呢? - merlin2011
算了,我以为你是因为除法的原因才这么说的。不过使用while try/except可能是更好的选择。 - Padraic Cunningham
@PadraicCunningham,非常合理的观点,但我尽可能少更改用户原始代码来回答问题。 - merlin2011
无论如何,它确实回答了问题。 - Padraic Cunningham

2

It will be

print "Tip = %.2f%%" % (100*float(tip)/meal)

结束标记%%打印百分号。数字(100*float(tip)/meal)是您要寻找的内容。

1
我们假设用户输入的是数字。 我们希望确保该数字是程序可以处理的有效百分比。 我建议预期用户对百分比的两种表达方式。 所以用户可能会键入.15515.5来表示15.5%。一个普通的if语句是确保这一点的一种方式(假设您已经转换为浮点数)。
if tip > 1:
    tip = tip / 100

或者,您可以使用所谓的三元表达式来处理此情况。在您的情况下,它应该是这样的:

tip = (tip / 100) if tip > 1 else tip

这里还有另一个问题, 你可以查看更多三元语法的相关信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接