3

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
DillM94
  • 71
  • 4
  • 3
    If you read input from the keyboard into a variable, the code for the plus sign is, well, '+' :) – Roy2012 Jun 03 '20 at 19:21
  • Have a look at this: https://stackoverflow.com/questions/24072790/detect-key-press-in-python – Sofien Jun 03 '20 at 19:23
  • @Shijith, that’s not valid syntax. `any` returns whether at least one of the values in an iterable is true. Maybe you meant something like `if operation in [“Addition”,”+”]:`? – Daniel Jun 03 '20 at 21:12

6 Answers6

2

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

Zephyr
  • 11,891
  • 53
  • 45
  • 80
2
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()
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
VTi
  • 1,309
  • 6
  • 14
1

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?")
JL Peyret
  • 10,917
  • 2
  • 54
  • 73
1

You might want to check this post from stackoverflow about detected key input in python with keyboard.is_pressed()

Zephyr
  • 11,891
  • 53
  • 45
  • 80
Noexit
  • 11
  • 2
0

You can use win32api

import win32api
import win32con
win32api.keybd_event(win32con.VK_F3, 0) # this will press F3 key
Zephyr
  • 11,891
  • 53
  • 45
  • 80
Ne1zvestnyj
  • 1,391
  • 1
  • 7
  • 25
0

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

r.purohit
  • 56
  • 4