python - 将数字增加百分之一的 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)
任何帮助将不胜感激,我仍然是菜鸟。
解决方案
if
Python 中的语句不需要括号。另外,不要重复自己。您在两个分支中都有相同的代码。如果您要进行乘法和除法,请按此顺序进行操作,以免丢失精度。此外,当您增加一个百分比时,您通常想要增加,而不是减少。
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)
推荐阅读
- powershell - 如何在一段时间内没有输出时杀死/停止powershell进程
- python - 单独文件中的 Python 函数:它们都需要相同的参数。如何在多个文件中创建全局变量?
- javascript - 通过 mongoose 将条目推送到 MongoDB 中的多级嵌套数组
- r - 为什么我没有使用 ggplot2 获得两个图例?
- flutter - 颤振项目无法在视觉工作室中运行
- javascript - 自动完成源响应
- python - 关于 extract() 函数的 Jupyter Notebook 命名组问题
- python - 引发异常时调用方法,在try块之后列出了多个异常
- java - 如何从字符串中只删除开始和结束的特殊字符?
- android-studio - Android Studio 没有重启