python - 简化代码-根据运算符执行数学运算

标签 python python-3.x lambda error-handling operators

这是Python中计算器的代码:

import time
#Returns the sum of num1 and num2
def add(num1, num2):
    return num1 + num2

#Returns the difference of num1 and num2
def subtract(num1, num2):
    return num1 - num2

#Returns the quotient of num1 and num2
def divide(num1, num2):
    return num1 / num2

#Returns the product of num1 and num2
def multiply(num1, num2):
    return num1 * num2

#Returns the exponentiation of num1 and num2
def power(num1, num2):
    return num1 ** num2

import time

def main ():
    operation = input("What do you want to do? (+, -, *, /, ^): ")
    if(operation != "+" and operation != "-" and operation != "*" and operation != "/" and operation != "^"):
        #invalid operation
        print("You must enter a valid operation")
        time.sleep(3)
    else:
        var1 = int(input("Enter num1: ")) #variable one is identified
        var2 = int(input("Enter num2: ")) #variable two is identified
        if(operation == "+"):
            print (add(var1, var2))
        elif(operation == "-"): 
            print (subtract(var1, var2))
        elif(operation == "/"): 
            print (divide(var1, var2))
        elif(operation == "*"):
            print (multiply(var1, var2))
        else:
            print (power(var1, var2))
main()
input("Press enter to exit")
exit()

大约30分钟前,我找到了旧的Python文件夹,并查看了8个月前的所有基本脚本。我找到了我的计算器迷你脚本,并认为以最少的行数重新创建它会很有趣(我现在正在学习lambda)。这是我所拥有的:
main = lambda operation,var1,var2: var1+var2 if operation=='+' else var1-var2 if operation=='-' else var1*var2 if operation=='*' else var1/var2 if operation=='/' else 'None'
print(main(input('What operation would you like to perform? [+,-,*,/]: '),int(input('Enter num1: ')),int(input('Enter num2: '))))
input('Press enter to exit')

我知道这是根据我的具体情况提出的一个个人问题,但我希望能将其缩短为任何帮助。有没有办法使它更Pythonic?我是否正确使用lambda?有没有办法处理我的简化版本中的错误?任何帮助,将不胜感激。我对此很陌生。谢谢!

最佳答案

为了简化代码,我建议:

  • 创建一个函数以借助字典进行操作。

    注意:根据用户提到的要求,我使用lambda函数来替代方法。我个人将使用 operator

    使用operator:
    import operator
    
    def perform_operation(my_operator):
        return {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.truediv,  # "operator.div" in python 2
            '^': operator.pow,
       }.get(my_operator, '^')  # using `^` as defualt value since in your 
                                # "else" block you are calculating the `pow` 
    

    使用lambda:
    def perform_operation(my_operator):
        return {
            '+': lambda x, y: x + y,
            '-': lambda x, y: x - y,
            '*': lambda x, y: x * y,
            '/': lambda x, y: x / float(y), 
            '^': lambda x, y: x ** y,
       }.get(my_operator, '^')  # using `^` as defualt value since in your 
                                # "else" block you are calculating the `pow()`
    

    sample 运行:
    >>> perform_operation('/')(3, 5)
    0.6
    

    PS:看一下定义,您会知道为什么使用operatorlambda更加pythonic
  • 更新您的else块以使其调用为:
    var1 = int(input("Enter num1: ")) 
    var2 = int(input("Enter num2: ")) 
    perform_operation(operation)(var1, var2)  # Making call to function created above
    # THE END - nothing more in else block
    
  • 使用以下方法简化if的条件:
    if operation not in ["+", "-", "*", "/", "^"]:
        # invalid operation
    
  • 关于python - 简化代码-根据运算符执行数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40255043/

    相关文章:

    javascript - 使用 html 数据属性中的字符串对 JSON 进行编码

    python-3.x - 了解 zlib header ; CMF(CM、CINFO)、FLG、(FDICT/DICTID、FLEVEL); RFC1950 § 2.2。数据格式

    c++ - 在 C++ 中将 lambda 表达式作为成员函数指针传递

    amazon-web-services - 从 Lambda 访问 EC2 中的文件

    python - 如何防止Python代码的目录遍历攻击

    python - Django 自定义过滤器

    python - MatPlotLib 中 LogLocator 的参数

    用于(简单)无向图的 Python 库/模块

    python - 创建深度复制时尝试 pickle 未知类型

    c# - 使用linq检查一个数组中的值是否存在于另一个数组中