[Python] How to make a calculator function that uses the operator as an input? [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I started writing a simple calculator in Python. 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(num1, num2, operator):
    print((str(num1)) + " " + str(operator) + " " + str(num2) + " = " + str(num1 **insert operator to compute equation** num2))


    What I have currently:

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

    Continue reading...

Compartilhe esta Página