简体   繁体   English

如何在 Python3 中简化我的计算器代码?

[英]How can I simplify my calculator code in Python3?

Hello I am trying to find out how I can simplify my code for a simple calculator.您好,我正在尝试找出如何简化简单计算器的代码。 My code is:我的代码是:

import sys
import operator


if len(sys.argv) != 4:
    print("Usage Error: $calc2.py OPERATION Number1 Number2")
else:
    operation = {
        "suma": operator.add(float(sys.argv[2]), float(sys.argv[3])),
        "resta": operator.sub(float(sys.argv[2]), float(sys.argv[3])),
        "multiplica": operator.mul(float(sys.argv[2]), float(sys.argv[3])),
        "divide": operator.truediv(float(sys.argv[2]), float(sys.argv[3])),
    }

    print(operation.__getitem__(sys.argv[1]))

I want to delete the line print(operation. getitem ... and put something inside the dictionary that prints me the value. Thanks我想删除行 print( operation.getitem ... 并在字典中放一些东西来打印我的值。谢谢

Maybe it is not simple - except operation - but it has few other useful elements.也许它并不简单——除了operation ——但它几乎没有其他有用的元素。

import sys
import operator

#sys.argv += ['resta', '1', '3'] # for test 
#sys.argv += ['other', '1', '3'] # for test
#sys.argv += ['suma', 'A', 'B'] # for test

operation = {
  "suma": operator.add,
  "resta": operator.sub,
  "multiplica": operator.mul,
  "divide": operator.truediv
}  

if len(sys.argv) != 4:
    print("Usage Error: $calc2.py OPERATION Number1 Number2")
else:
    op = operation.get(sys.argv[1])  # it returns None if it can't get it
    if not op:
        print('Wrong operation:', sys.argv[1], '\nIt has to be: suma, resta, multiplica, divide.')
    else:
        try:
            print(op(float(sys.argv[2]), float(sys.argv[3])))
        except ValueError as ex:
            print('Wrong value(s):', sys.argv[2], sys.argv[3], '\nIt have to be float numbers.')

There is a common pattern involving dictionaries and operators, more like this:有一个涉及字典和运算符的常见模式,更像这样:

import sys, operator

operation = {"suma":       operator.add,
             "resta":      operator.sub,
             "multiplica": operator.mul,
             "divide":     operator.truediv}

if len(sys.argv) != 4:
    print("Usage Error: $calc2.py OPERATION Number1 Number2")
else:
    A, B = float(sys.argv[2]), float(sys.argv[3])

    result = operation[sys.argv[1]](A, B)

    print(result)

Some flaws with your original version were that all of the operations get calculated every time (eg performing division even if addition is requested, sometimes causing irrelevant division by zero errors), and that there was no purpose to using functional operators (instead of standard +-/* arithmetic syntax).原始版本的一些缺陷是每次都会计算所有操作(例如,即使请求加法也执行除法,有时会导致不相关的零错误除法),并且没有目的使用函数运算符(而不是标准+-/*算术语法)。

For error handling you could use something like:对于错误处理,您可以使用类似的东西:

    try:
        result = operation[sys.argv[1]](A, B)
    except KeyError:
        print('Usage Error: {0} must be one of {1}'
              .format(sys.argv[1], ','.join(operation.keys()))
    else:
        print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM