简体   繁体   中英

How to make Python calculate result of percentage?

I want Python to be able to the calculate the result of a percentage.

For example: If a drink costs 8, calculate what it costs with 20% added tips (or whatever given percentage).

It then should be 9.6 of course. I thought I might be able to do it with code something like this:

drink = 8 + 20%

Python doesn't support expressing percentages with the % symbol. It can multiply, however.

Increasing a value by 20% means multiplying it by 1.2.

drink = 8 * 1.2

You could write a function if you want to give the percentage and derive the factor:

def add_tips(value, percentage):
    return value * (1 + percentage / 100)
>>> drink = 8
>>> add_tips(drink, 20)
9.6

The possibilities are endless.

You can always translate percentages to a floating-point value like 20% = 0.2 or 81.7% = 0.817 . So simply divide by 100 to transform percentage to floating-point number. In your case, you want to add 20% of a number to this number aka you want 120% of this number which equates to multiplying with 1.2 . You can also validate this by calculating 8 + (8 * 0.2) which might be more intuitive.

给定原始成本和百分比,您可以这样做以获得总金额。

totalCost = cost + (percentage/100)*cost

Python does support the expression of percentages, thanks to the str format() . If you like, you can even mimic that behavior in a unittest.

Example code:

def divideby4(x):
    return "{0:.0%}".format(x/4)

Example test:

import unittest
import some_silly_calc

class TestCalc(unittest.TestCase):
... 

    def test_divide(self):
        result = some_silly_calc.divideby4(2)
        self.assertEqual(result, "{0:.0%}".format(.50))

Alternative method if you don't want to use "%":

def divideby4(x):
    return (x / 4 * 100)

I love how much Python 3+ has evolved since Python 2.7. So many cool features! HTH :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM