I started learning Python yesterday; this is the first calculator I've made. I noticed that the last lines of code that print the equation's result are repeated.

Can I write a function that takes the operator as input and then prints the result with just one line of code?

I imagine it would be something like this:

def result(operator):

print((str(num1)) + " " + str(operator) + " " + str(num2) + " = " + str(num1 insert operator to compute equation num2))

    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))

推荐答案

You might try using a dictionary to map strings (operators) to function objects:

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}")

In this case, add, sub, mul and floordiv are the function objects, each of which take two parameters, and return a number.

Python相关问答推荐

Geopandas未返回正确的缓冲区(单位:米)

幂集,其中每个元素可以是正或负""""

使用Openpyxl从Excel中的折线图更改图表样式

计算空值

我对这个简单的异步者的例子有什么错误的理解吗?

从一个df列提取单词,分配给另一个列

有没有办法在不先将文件写入内存的情况下做到这一点?

python的文件. truncate()意外地没有截断'

浏览超过10k页获取数据,解析:欧洲搜索服务:从欧盟站点收集机会的微小刮刀&

Scipy差分进化:如何传递矩阵作为参数进行优化?

pytest、xdist和共享生成的文件依赖项

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

大型稀疏CSR二进制矩阵乘法结果中的错误

如何使用count()获取特定日期之间的项目

对齐多个叠置多面Seborn CAT图

如何获得症状表达式的真实部分?

如何从matplotlib中的Splter()中获取 colored颜色 条或图例?

如何根据预定义的模板重新排序YAML键并维护注释?

极轴:通过创建多个新列对列进行操作

递归函数根据词法作用域的不同而失败