0

THis may have been asked before so apologies but i literally just started 'learning' Python 3 two days ago.

As part of an exercise you build a very simple calculator but all it can do is one operation at a time (i.e. result = variable 1 +-* variable 2 ) how do i get the result to take into account my operator variable?

num1 = float(input("Enter a Number Greater than 1: "))
oper = input("Choose a math Operation (+, -, /, *) :")
num2 = float(input("Enter another Number: "))
result = float(num1) oper float(num2)
print(result)

I am told mapping the operator to a function like lambda, but how do i do this exactly ? The gist is i want to just be able to use a divide, add, multiply and minus operator between the Input statements. i wrote

num1 = float(input("Enter a Number Greater than 1: ")) + = lambda num1,num2 : num1 + num2 * = lambda num1,num2 : num1 * num2 - = lambda num1,num2 : num1 - num2 / = lambda num1,num2 : num1 / num2 num2 = float(input("Enter another Number: ")) result = float(num1) oper float(num2) print(result)
Rami Aboulissane
  • 23
  • 1
  • 1
  • 4
  • You need to map the operator to a function, and call the function. You can use a dictionary to hold the mapping, e.g. `{"+": lambda x, y: x + y}` – Barmar Apr 22 '22 at 14:23
  • You need to convert the string `oper` to a function which takes `float(num1)` and `float(num2)` as arguments. There are lots of ways to do this, but the simplest involves a `dict` and the `operator` module. – chepner Apr 22 '22 at 14:24
  • THanks for the tips guys but honestly my logic is probably terrible. The gist is i want to just be able to use a divide, add, multiply and minus operator between the Input statements. i wrote `num1 = float(input("Enter a Number Greater than 1: ")) + = lambda num1,num2 : num1 + num2 * = lambda num1,num2 : num1 * num2 - = lambda num1,num2 : num1 - num2 / = lambda num1,num2 : num1 / num2 num2 = float(input("Enter another Number: ")) result = float(num1) oper float(num2) print(result)` – Rami Aboulissane Apr 27 '22 at 12:50

0 Answers0