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
Maybe it is not simple - except operation
- but it has few other useful elements.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.