python - 基本计算器不适用于我的功能
问题描述
所以我在 Python 3.7 中编写了一个简单的计算器,但它不适用于我的函数。变量“输出”是灰色的,但我不知道为什么。
n1 = 0
n2 = 0
op = 0
res = 0
output = 0
# DEFINING FUNCTIONS
def askAndStore(aasText,var2save):
print(aasText)
var2save = input()
def calculate(num1,num2,op,output):
if op == "add":
output = float(num1) + float(num2)
elif op == "sub":
output = float(num1) - float(num2)
elif op == "mul":
output = float(num1) * float(num2)
elif op == "div":
output = float(num1) / float(num2)
else:
print("Error: Unknown operation")
# PROGRAM MAIN
askAndStore("What is the first number?", n1)
askAndStore("What is the second number?", n2)
askAndStore("What is the operation?", op)
calculate(n1, n2, op, res)
print(res)
我的输出是:
What is the first number?
10
What is the second number?
5
What is the operation?
add
Error: Unknown operation
0
Process finished with exit code 0
它总是显示“错误:未知操作”,即使我输入“添加”作为操作。任何想法为什么它不起作用?
解决方案
n1 = float(input("What is the first number? "))
n2 = float(input("What is the second number? "))
op = str(input("What is the operation? "))
# DEFINING FUNCTIONS
def calculate(num1, num2, opr):
if opr == "add":
output = num1 + num2
elif opr == "sub":
output = num1 - num2
elif opr == "mul":
output = num1 * num2
elif opr == "div":
output = num1 / num2
else:
print("Error: Unknown operation")
return output
print(calculate(n1, n2, op))
推荐阅读
- node.js - 在 Angular 项目 Visual Studio 代码上启动前端时出错
- svg - Highcharts在svg标记上填充serie的颜色
- reactjs - DashboardMenuItem 活动资源
- list - Haskell 检查整数第一个元素以处理 ID 号
- c++ - 在具有大量输入的 C++ 中使用向量时出现运行时错误
- momentjs - 日期格式无法使用 momentjs
- docker - Kafka Connect,插件路径
- android-mediacodec - 如何解释 MediaCodec 错误消息?
- node.js - 在 AWS lambda 中使用 airtable.js 模块的问题
- firebase - 从 Firestore 加载繁重的文档是否需要很长时间?