How to use '+' as input

Viewed 144

I've just started to learn python. I'm trying to make a calculator as an intro project. For addition I've written:

if operation == "Addition":
    print("The answer is: " +str(num1+num2))

Later on the program asks what operation you want to perform. Instead of typing Addition I'd like to instead press the + key on my keyboard. Can I do this? I imagine the + key has some sort of code that I need to find?

6 Answers

The simplest answer I know is this: put all the possible options in a list and check if the user input is present in that list:

options = ['Addition', 'addition', 'add', '+', 'sum', 'Sum']

if operation in options:
    print("The answer is: " +str(num1+num2))

The advantage is that you can include any possible combination that the user could enter

op = input('please input the operation sign')
num1 = input('Enter first number')
num2 = input('Enter second number')

if (op == '+'):
    print("The answer is: " + str(int(num1) + int(num2)))
else:
    quit()

You can use win32api

import win32api
import win32con
win32api.keybd_event(win32con.VK_F3, 0) # this will press F3 key

Check out operator module.

import operator

#tons of other math functions there...
di_op = {"+" : operator.add, "add" : operator.add}


num1 = 1
num2 = 2
operation = "+"


print(di_op[operation](num1,num2))

output:

3

I.e. lookup the function in the dict - square brackets, then call the function you found using parenthesis and your nums.

for the prompt, this ought to do it, as long you press Enter.

operation = input("whatcha wanna do?")
Related