首页 > 解决方案 > 将数字增加百分之一的 Python 脚本

问题描述

所以,我已经在这个项目上工作了很长一段时间,但我似乎无法弄清楚这一点。我已经编写了将数字增加百分之一的脚本,但我不断收到此错误:

File "C:\Users\jacob\Python Scripts\Percent.py", line 11, in <module>
    value = str(num + ((num / 100) * percent))
TypeError: unsupported operand type(s) for /: 'str' and 'int'

我不知道为什么会这样,但这是我的代码。

value = ""
print("Number increase or decrease by percent")
print("")
print("Increase or decrease:") 
input = input()
if (input == "increase"):
    print("Number:") 
    num = input()
    print("Percent:") 
    percent = input()
    value = str(num - ((num / 100) * percent))
    print(value)
if (input == "decrease"):
    print("Number:") 
    num = input()
    print("Percent:") 
    percent = input()
    value = str(num - ((num / 100) * percent))
    print(value)

任何帮助将不胜感激,我仍然是菜鸟。

标签: pythonmath

解决方案


ifPython 中的语句不需要括号。另外,不要重复自己。您在两个分支中都有相同的代码。如果您要进行乘法和除法,请按此顺序进行操作,以免丢失精度。此外,当您增加一个百分比时,您通常想要增加,而不是减少。

print("Number increase or decrease by percent")
print("")
print("Increase or decrease:") 
option = input()
print("Number:") 
num = int(input())
print("Percent:") 
percent = int(input())
if option == "increase":
    value = num + (num * percent / 100)
if option == "decrease":
    value = num - (num * percent / 100)
print(value)

推荐阅读