Reputation: 73
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?
Upvotes: 3
Views: 165
Reputation: 1397
You can use win32api
import win32api
import win32con
win32api.keybd_event(win32con.VK_F3, 0) # this will press F3 key
Upvotes: 0
Reputation: 11
You might want to check this post from stackoverflow about detected key input in python with keyboard.is_pressed()
Upvotes: 1
Reputation: 12506
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
Upvotes: 2
Reputation: 12204
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))
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?")
Upvotes: 1
Reputation: 1319
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()
Upvotes: 2
Reputation: 56
PyGame has those type of keypress features. Use a library such as pygame which will do what you want. Pygame contains more advanced keypress handling than is normally available with Python's standard libraries.
Here is the documentation: https://www.pygame.org/docs/
here are the .key docs: https://www.pygame.org/docs/ref/key.html
Upvotes: 0