shortening a calculator in python -


i have managed create small calculator in python, trying shorten code unsucsessfully. can 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 not able 2 operations @ once either.

use functions operator module or simple functions define calculation work, map operation name queencommand string 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 replaced lambda a, b: + b, etc. if don't want use module operations.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -