如何使用“+”作为输入

How to use '+' as input

我刚开始学习python。我正在尝试制作一个计算器作为介绍项目。另外我写了:

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

稍后程序会询问您要执行什么操作。我不想输入 Addition,而是按键盘上的 + 键。我可以这样做吗?我想 + 键有某种我需要找到的代码?

您可以使用win32api

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

PyGame 具有这些类型的按键功能。使用诸如 pygame 之类的库,它将执行您想要的操作。 Pygame 包含比 Python 的标准库通常可用的更高级的按键处理。

这是文档: https://www.pygame.org/docs/

这是 .key 文档: https://www.pygame.org/docs/ref/key.html

我知道的最简单的答案是:将所有可能的选项放在一个列表中,然后检查该列表中是否存在用户输入:

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

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

优点是您可以包含用户可以输入的任何可能的组合

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()

检查 operator 模块。

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

即在 dict - 方括号中查找函数,然后使用括号和你的 nums 调用你找到的函数。

对于提示,只要按回车就可以了。

operation = input("whatcha wanna do?")

您可能需要查看 this post from Whosebug about detected key input in python with keyboard.is_pressed()