How to make a calculator function that uses the operator as an input?

Question:

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))
Asked By: asdfghjkl

||

Answers:

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.

Answered By: Paul M.
number1 = int(input("pick a number "))
number2 = int (input("pick another number "))


def addition(number1,number2):
  sum = (number1 + number2)
  return sum

sum = addition(number1,number2)
print(sum)






def multiplication(number1,number2):
  product = (number1 * number2)
  return product

product = multiplication(number1,number2)
print(product)



def devision(number1,number2):
  quotient = (number1 / number2)
  return quotient

quotient = devision(number1,number2)
print(quotient)



def subtraction(number1,number2):
  remander = (number1 - number2)
  return remander


remander = subtraction(number1,number2)
print(remander)
Answered By: Julian Machado

I would use this method to keep it simple yet powerful.

  1. first generate an expression using fstring
  2. execute eval with the expression: The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
first = float(input("Enter the first number: "))
second = float(input("Enter second number: "))
operator = str(input("Enter operator: "))

# add checks for the operator
allowed_ops = ["+", "-", "*", "/"]
if operator not in allowed_ops:
    raise Exception(f"Operator {operator} not allowed. Allowed operators are '{', '.join(allowed_ops)}'.")

# execute the expression
result = eval(f"{first} {operator} {second}")

print(result)
Answered By: pKiran
print('''
1. +
2. -
3. *
4. /
5. exit
''')

while True:
    op = input("please choice the operation? ")
    num1 = float(input("please insert first number? "))
    num2 = float(input("please insert second number? "))

    if op == "+":
        result = (num1 + num2)
        print("result is:", result)
    elif op == "-":
        result = (num1 - num2)
        print("result is:", result)
    elif op == "*":
        result = (num1 * num2)
        print("result is:", result)
    elif op == "/":
        result = (num1 / num2)
        print("result is:", result)
    elif op == "exit":
        break
Answered By: sky_iran4433
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.