1

i just started coding for fun and i'm trying to build a calculator that uses userinput. 2 numbers and one operator. I'm realy realy new to coding and currently limited to very simple use of if statements and while/for loops and i just started looking into functions. I have been trying to put this code into a function for a while but i can't find a solution to use the string "operator" as an actual operator in the function.

there must be a way to make all of this shorter.

if used_op == "+":
    print(">  " + str(number_1) + " + " + str(number_2) + " = " + str(number_1 + number_2) + "  <")
elif used_op == "-":
    print(">  " + str(number_1) + " - " + str(number_2) + " = " + str(number_1 - number_2) + "  <")
elif used_op == "*":
    print(">  " + str(number_1) + " * " + str(number_2) + " = " + str(number_1 * number_2) + "  <")
elif used_op == "/":
    print(">  " + str(number_1) + " / " + str(number_2) + " = " + str(number_1 / number_2) + "  <")
elif used_op == "%":
    print(">  " + str(number_1) + " % " + str(number_2) + " = " + str(number_1 % number_2) + "  <")
elif used_op == "**":
    print(">  " + str(number_1) + " ** " + str(number_2) + " = " + str(number_1 ** number_2) + "  <")
elif used_op == "//":
    print(">  " + str(number_1) + " // " + str(number_2) + " = " + str(number_1 // number_2) + "  <")

What I tried is something like this:

def solve(op):
    print(">  " + str(number_1) + op + str(number_2) + " = " + str(
        number_1 + **op** + number_2) + "  <")

solve(used_op)

I tried to find a solution for this on the internet for a while but i had no luck so far.

2 Answers 2

2

You can use a dictionary and the operator module to do what you want:

import operator

# this will act like a sort of case statement or switch
operations = {
    '>': operator.gt,
    '<': operator.lt,
    '=': operator.eq,
    '+': operator.add,
    '-': operator.sub,
    '/': operator.div,
    '*': operator.mul,
    '**': operator.pow,
    '//': operator.floordiv,
    ... # so on and so forth
}

def calculate(num1, num2, op):
    # operation is a function that is grabbed from the dictionary
    operation = operations.get(op)
    if not operation:
         raise KeyError("Operation %s not supported"%op)

    # Call the operation with your inputs
    num3 = operation(num1, num2)
    print('%3.2f %s %3.2f = %3.2f' % (num1, op, num2, num3))


calculate(1,2, '+')
# 1.00 + 2.00 = 3.00

Sign up to request clarification or add additional context in comments.

Comments

-1

Simply evaluate your mathematical expression and python will do the rest of the job for you.

This can of course be done with the in-built eval() function.

Here are some examples how you can use it:

>>> eval("1+1")
2

>>> A = 2
>>> eval("A * 3")
6

The function that you're trying to write, could look something like this

def solve(a, b, op):
    expression = str(a) + op + str(b)
    print("> " + expression + "=" + str(eval(expression)))

solve(1, 2, "+")   # > 1+2=3
solve(10, 10, "*") # > 10*10=100
solve(4, 2, "/")   # > 4/2=2.0
solve(5, 10, "-")  # > 5-10=-5

6 Comments

i like this alot! looks very clean and elegant.
No problem! It's worth noting that the previously accepted answer is generally speaking more "proffesional", however when it comes to simplicity, I would say this is the way to go.
to be honest i'm just not there yet, to really understand the other answer. i tryed it out and it worked. but i should understand it in order to use it.
I'd agree that this answer is quite simple and easy to read. However, eval is usually seen as a bad practice and not something to be used lightly. For this example, there's no harm, just a heads up in future answers
well i'm sad now, i wrote a calculator programm with 80 lines and it took me like 5h. and its far from perfect. now i realized that: expression = input("Enter calc: ") print("> " + expression + " = " + str(eval(expression)) + " <") does everything and more then my program :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.