如何在 Python 中找到变量的百分比?

Wil*_*ard 0 python

我不知道如何在 Python 中找到变量的百分比。这是代码示例:

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
Run Code Online (Sandbox Code Playgroud)

它总是只加 21,因为它看到 5%,并给出等式(5% 的钱)的值为 5。

Pie*_*agh 5

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

\n\n

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.

\n\n
>>> 9 % 4\n1\n>>> 9 % 3\n0\n
Run Code Online (Sandbox Code Playgroud)\n\n

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!

\n\n

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?

\n\n

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".

\n\n
\n\n

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

\n\n
money = 546.97\nfor i in range(10):\n    week = i * 4\n    money += 16\n    money += (0.05 * money)\n    print("On week {week} you have {money:.2f} dollars.".format(week=week, money=money))\n
Run Code Online (Sandbox Code Playgroud)\n\n

I made a few adjustments:

\n\n
    \n
  • Instead of manually incrementing both i and week, let the loop take care of that;\xc2\xa0that\'s what it\'s for, after all!
  • \n
  • Replaced (5% money) with (0.05 * money), which is how Python will understand what you want
  • \n
  • Replaced your print statements with a single statement\n\n
      \n
    • 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)
    • \n
    • 有关这些参数如何工作的更多信息,请参阅6.1.3 \xe2\x80\x94\xc2\xa0Format String Syntax
    • \n
  • \n
  • 替换语句如money = money + xwithmoney += x because it\'s more concise and easier to read to advanced programmers (in my opinion)
  • \n
  • 调整运算符周围的空白以提高可读性
  • \n
\n