我昨天开始学习Python,这是我做的第一个计算器.我注意到打印公式结果的最后几行代码是重复的.

我是否可以编写一个函数,将操作符作为输入,然后只用一行代码打印结果?

我想应该是这样的:

定义结果(运算符):

Print((STR(数字1)+"+STR(运算符)+"+STR(数字2)+"="+STR(数字1 insert operator to compute equation数字2)

    num1 = float(input("Enter first number: "))

    op = None
    while op not in ("-", "+", "*", "/"):
        op = input("Enter operator (-, +, *, /):  ")

    num2 = float(input("Enter second number: "))

    if op == "-":
      print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 - num2))
    elif op == "+":
      print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 + num2))
    elif op == "*":
      print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 * num2))
    elif op == "/":
      print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 / num2))

推荐答案

您可以try 使用字典将字符串(运算符)映射到函数对象:

from operator import add, sub, mul, floordiv

operations = {
    "+": add,
    "-": sub,
    "*": mul,
    "/": floordiv
}

a = float(input("Enter first number: "))

while (op := input("Enter operator: ")) not in operations: pass

# 'operation' is one of the four functions - the one 'op' mapped to.
operation = operations[op]

b = float(input("Enter second number: "))

# perform whatever operation 'op' mapped to.
result = operation(a, b)

print(f"{a} {op} {b} = {result}")

在本例中,addsubmulfloordiv是函数对象,每个对象都有两个参数,并返回一个数字.

Python相关问答推荐

按列分区,按另一列排序

如何制作10,000年及以后的日期时间对象?

Python,Fitting into a System of Equations

什么是最好的方法来切割一个相框到一个面具的第一个实例?

未知依赖项pin—1阻止conda安装""

Django RawSQL注释字段

找到相对于列表索引的当前最大值列表""

并行编程:同步进程

使用类型提示进行类型转换

递归链表反转与打印语句挂起

Scipy.linprog的可行性有问题吗?(A_ub@x0<;=b_ub).all()为True-但是-linprog(np.zeros_like(X0),A_ub=A_ub,b_ub=b_ub)不可行

为什么在更新Pandas 2.x中的列时,数据类型不会更改,而在Pandas 1.x中会更改?

如何在Django查询集中生成带有值列表的带注释的字段?

Django-修改后的管理表单返回对象而不是文本

Pandas查找给定时间戳之前的最后一个值

是否从Python调用SHGetKnownFolderPath?

我应该使用哪一个来判断python中枚举值的唯一性?

SQL模型中包含日期时间的TypeError

在Matplotlib中通过特定的Y值而不是 colored颜色 来改变alpha/opacity

从pandas框架中删除重复的子框架