0

I can't figure out how you find a percentage of a variable in Python. This is the example of the code:

money =546.97
week=0
for i in range(10):
    money=money+16
    money=money+(5% money)
    print('you have',money,'dollars')
    week=week+4
    print(week)
i = i +1

It always just adds 21 because it sees 5% and gives the equation (5% money) the value of 5.

Pierce Darragh
  • 2,072
  • 2
  • 16
  • 29
Will Shepard
  • 135
  • 1
  • 1
  • 7

2 Answers2

5

While the % symbol means "percent of" to us, it means an entirely different thing to Python.

In Python, % is the modulo operator. Takes the thing on the left, divides it by the thing on the right, and returns the remainder of the division.

>>> 9 % 4
1
>>> 9 % 3
0

So when you do 5% money, Python reads it as "divide 5 by money and return the remainder". That's not what you want at all!

To answer the question, we need to look at what a percentage is. Percent comes from Latin per cent, meaning "per one hundred things". So "five percent" literally means "take five out of every hundred things." Okay, great! So what?

So to find a percentage of a number, you must multiply that number by its decimal percentage value. 5% is the same thing as 0.05, because 0.05 represents "five one-hundredths" or "five things for every hundred things".


Let's rewrite your code a little bit (and I'll clean up the formatting somewhat).

money = 546.97
for i in range(10):
    week = i * 4
    money += 16
    money += (0.05 * money)
    print("On week {week} you have {money:.2f} dollars.".format(week=week, money=money))

I made a few adjustments:

  • Instead of manually incrementing both i and week, let the loop take care of that; that's what it's for, after all!
  • Replaced (5% money) with (0.05 * money), which is how Python will understand what you want
  • Replaced your print statements with a single statement
    • Used the advanced formatting {__:.2f} to produce a number that cuts off to just two decimal places (which is usual for money, but you can erase the :.2f if you want the full floating-point value)
    • See 6.1.3 — Format String Syntax for more information about how these arguments work
  • Replaced statements like money = money + x with money += x because it's more concise and easier to read to advanced programmers (in my opinion)
  • Adjusted whitespace around operators for readability
Pierce Darragh
  • 2,072
  • 2
  • 16
  • 29
1

The % symbol in python is the modulo operator in python.

It doesn't compute a percent, rather x % y determines the remainder after dividing x by y.

If you want the percentage of a variable, you just have to multiply it by the decimal value of the percent:

money * .05
# 5 % of money
Community
  • 1
  • 1
xgord
  • 4,606
  • 6
  • 30
  • 51