【问题标题】:How to use '+' as input如何使用“+”作为输入
【发布时间】:2020-09-22 15:10:47
【问题描述】:

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

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

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

【问题讨论】:

  • 如果你从键盘读取输入到一个变量中,加号的代码就是'+' :)
  • @Shijith,这不是有效的语法。 any 返回可迭代对象中的至少一个值是否为真。也许你的意思是if operation in [“Addition”,”+”]:
  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 位于答案左上角的 / 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您也可以使用 / 箭头对答案的有用性进行投票。 如果解决方案不能回答问题,请发表评论What should I do when someone answers my question?。谢谢

标签: python calculator


【解决方案1】:

您可以使用win32api

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

【讨论】:

    【解决方案2】:

    PyGame 具有这些类型的按键功能。使用诸如 pygame 之类的库来满足您的需求。 Pygame 包含比 Python 标准库通常可用的更高级的按键处理。

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

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

    【讨论】:

      【解决方案3】:

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

      options = ['Addition', 'addition', 'add', '+', 'sum', 'Sum']
      
      if operation in options:
          print("The answer is: " +str(num1+num2))
      

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

      【讨论】:

        【解决方案4】:
        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()
        

        【讨论】:

          【解决方案5】:

          查看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 - 方括号中查找函数,然后使用括号和您的数字调用您找到的函数。

          对于提示,应该这样做,只要你按Enter键。

          operation = input("whatcha wanna do?")
          

          【讨论】:

            【解决方案6】:

            您可能希望使用 keyboard.is_pressed() 从 stackoverflow 检查 this post 关于在 python 中检测到的键输入

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-11-06
              • 2021-07-26
              • 2021-04-09
              • 2021-11-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多