0

I'm messing around trying to make a calculator and I have 2 user inputs and an operation:

num1 = float(input("Enter first number: "))
op = input("Enter an operation: ")
num2 = float(input("Enter a second number: "))

and I want to make a variable for the result number:

num3 = float(num1 + op + num2)

but I don't know how to separate the operation so it will still be a string

Shane
  • 1
  • If `2` and `3` are entered `num3` should be `5`? – user3783243 Sep 22 '20 at 19:01
  • 1
    `op` already *is a string*. That isn't the problem. The problem is you can't use a `str` like that. Not, to solve the proximal problem, `num1` and `num2` should just be strings, but your fundamental problem is that `float("2.0 + 2.0")` is not going to work. You probably want to use `eval`, although, that is almost *never* the right approach in realistic scenarios. – juanpa.arrivillaga Sep 22 '20 at 19:02
  • You want to apply the string `op` as a real operator ? – azro Sep 22 '20 at 19:02
  • `ast` library and `literal_eval` might be a safe approach to take. https://docs.python.org/3/library/ast.html#ast.literal_eval – Mark Cook Sep 22 '20 at 19:03
  • if you only have 2 numbers and 1 operator, you can try if clauses: `if op == "+": num1+num2` – Wups Sep 22 '20 at 19:06
  • According to the answer by [Amnon][1], You can use operator library in python and add all the symbols required. For your use case, you can write num3 = ops[op](num1,num2) [1]: https://stackoverflow.com/a/1740759/10451749 – Pritesh Gohil Sep 22 '20 at 19:07
  • Sorry, I forgot to add the middle section I made. Before I get num3 I have a list of if and elif statements for various operations: `if op == "+":` ` print(num1 + num2)` `elif op == "-":` ` print(num1 - num2)` `elif op == "*":` ` print(num1 * num2)` `elif op == "/":` ` print(num1 / num2)` `elif op == "^":` ` print(num1 ** num2)` `else:` ` print("Invalid")` – Shane Sep 22 '20 at 19:54
  • I want to have a result number and the way I thought to do it was to take whatever the user input was for num1 and num2 and use it with their input for the operation, then make it = num3 – Shane Sep 22 '20 at 20:06

0 Answers0