我不知道如何在 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
它总是只加 21,因为它看到 5%,并给出等式(5% 的钱)的值为 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\n1\n>>> 9 % 3\n0\nSo 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?
\n\nSo 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).
\n\nmoney = 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))\nI made a few adjustments:
\n\ni and week, let the loop take care of that;\xc2\xa0that\'s what it\'s for, after all!(5% money) with (0.05 * money), which is how Python will understand what you want{__:.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)money = money + xwithmoney += x because it\'s more concise and easier to read to advanced programmers (in my opinion)| 归档时间: | 
 | 
| 查看次数: | 2109 次 | 
| 最近记录: |