【问题标题】:How to turn input number into a percentage in python如何在python中将输入数字转换为百分比
【发布时间】:2015-01-25 23:11:25
【问题描述】:
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)

当有人输入数字时成为百分比。

【问题讨论】:

标签: python python-3.x


【解决方案1】:
>>> "{:.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% 小费?
    • 我认为你的意思是出于分裂原因。一段时间尝试/除了可能是一个更好的选择
    • @PadraicCunningham,一个非常合理的观点,但我试图通过尽可能少地改变用户的原始代码来解决这个问题。
    • 好吧 +1 它确实回答了这个问题。
    【解决方案3】:

    会的

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

    结尾%% 打印百分号。号码(100*float(tip)/meal) 就是您要找的号码。

    【讨论】:

      【解决方案4】:

      我们假设这是用户输入的数字。我们希望确保该数字是程序可以使用的有效百分比。我建议从用户那里预测百分比的两种表达方式。所以用户可以输入.15515.5 来代表15.5%。普通的 if 语句是解决此问题的一种方法。 (假设您已经转换为浮点数)

      if tip > 1:
          tip = tip / 100
      

      或者,您可以使用所谓的三元表达式来处理这种情况。在您的情况下,它看起来像这样:

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

      您可以查看another question here 以了解有关三元语法的更多信息。

      【讨论】:

        猜你喜欢
        • 2012-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多