1

How do I make this code work so that the operator that gets typed in will be the operation between two numbers?

First = input("First Number: ")
Operator = input("Operator: ")
Second = input("Second Number: ")
Sum = float(First) Operator float(Second)
print(Sum)
Isakbanton
  • 11
  • 1

7 Answers7

2

I think, the safest and the most explicit way would be to have a dict of the operators, e.g.:

import operator
known_operators = {
    '+': operator.add,  # alternatively: '+': lambda x, y: x + y
    '*': operator.mul,
    # etc
}   

# ...
result = known_operators[op](v1, v2)
bereal
  • 32,519
  • 6
  • 58
  • 104
  • 1
    Heh, never knew the `operator` module existed, that would have saved me typing a lot of double underscores over the years. – Peter Dec 01 '21 at 12:10
1

Simplest way to do it: Use eval.

First = float(input("First Number: "))
Operator = input("Operator: ")
if Operator in ('+', '-', '*', '/'):
    Second = float(input("Second Number: "))
    print(eval(f"{First} {Operator} {Second}"))
else:
    print("Enter correct operator!")

Note: Eval can be used to execute any python code. Therefore you need always to check user input.

Ratery
  • 2,863
  • 1
  • 5
  • 26
  • Simplest, but also the most "dangerous" https://stackoverflow.com/questions/18269797/what-does-eval-do-and-why-its-evil – Tzane Dec 01 '21 at 12:02
  • Thanks, I know about it. Therefore my code checks user input. – Ratery Dec 01 '21 at 12:04
1

Welcome to StackOverflow :)

There isn't such a simple way to do an operation between First and Second variables. You should check the operation variable and then do that operation:

if operation == '+':
    ans = First + Second
elif operation == '-':
    ans = First - Second
...
Ali Irani
  • 557
  • 3
  • 10
1

Just moving my comment to an answer. There are extremely few cases where eval should be used, and this is not one of them. It adds unnecessary security risks to your script, and while this particular use case is quite simple, you're better off just not getting into the habit of using it.

I would suggest mapping the operators to the actual methods that are run, and calling the method (eg. 5 + 10 is actually int(5).__add__(10)). See here for more information on these.

operators = {
    '+': '__add__',
    '-': '__sub__',
    '*': '__mul__',
    '/': '__div__',
}

First = input("First Number: ")
Operator = input("Operator: ")
Second = input("Second Number: ")
Sum = getattr(float(First), operators[Operator])(float(Second))
print(Sum)
Peter
  • 3,186
  • 3
  • 26
  • 59
0

An easy way to do so is to use eval().

Sum = eval(f"{float(First)} {Operator} {float(Second)}")

But BEWARE ! eval() is considered a very insecure function, because it allows execution of arbitrary code. Unless you absolutely trust the final user of your code, you should thoroughly validate all input before passing it to eval().

Depending of the ultimate goal of your code, a much safer way would be writing a dictionary of the operators you accept, mapping strings like '+' into operator functions (operator.add() and the like).

-1

Isakbanton, you can use eval(). The eval operation takes any text and tries to do math with it. Ex:

eval("5+5") #returns 10

Anyways here is an answer to your problem.

print(eval("%s%s%s"%(float(First),Operator,float(Second))))
-1

I think you can try this:

    Sum= eval(First+Operator+Second)
    print(Sum)
Hasan Riza
  • 469
  • 1
  • 8