not even slightly a pc god February 2016
### shortening a calculator in python

I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?

```
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
```

I am not able to do two operations at once either.

Use functions from the `operator`

module or simple functions you define yourself to the calculation work, then map the operation name from the `queencommand`

string to those functions:

```
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
```

`operator.add`

could be replaced by `lambda a, b: a + b`

, etc. if you don't want to use a module for those operations.

Asked in February 2016

Viewed 1,014 times

Voted 6

Answered 1 times

Viewed 1,014 times

Voted 6

Answered 1 times