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相关问答推荐

是否可以使用 python 解决演绎推理测试问题?

如何从 keras 导入 resnet_rs 模块?

检索图像 src 属性并进行比较时,BeautifulSoup 出现问题

如何在 Django ORM 中加入子查询

如何在python中动态创建的函数中对变量进行硬编码?

更新字典在循环中不起作用

Python3,二进制数据与我需要的不同表示

如何获得连续条件的最大值为真?

Python 线程进程不会阻止“无响应”

使用 eval 时 locals() 字典的奇怪行为

如何使用 Selenium 和 Python 使用 if-else 逻辑单击元素或其他元素以实现自动化机器人

当我只想要最后一个时获取多个列表

Python websockets 模块和 IIS 作为反向代理

Pandas:str.extract() 给出了意想不到的 NaN

根据条件复制 Pandas 数据框中的行并更改特定列的值

我可以在python中重载->吗?

我应该如何打破这个问题的循环?

Tkinter 窗口不显示小部件

如何得到没有.目录中以 .docx 和 .doc 结尾的文件的字符数,并将每个文件的字符除以 65 并将它们保存到 xlsx

如何有效地找到一个平方等于另一个立方的数对?