I'm a python beginner and I'm practicing a simple calculation class.
This piece of code is supposed that when user input 2 numbers and 1 operator in the command line, it will show you the answer. I just wonder why it prints 4 lines in function add(), subtract(), multiply() and divide(). I just put them in a dictionary, not call all of them. Could anybody explain that for me please? It would be great to show me the solution as well. Thanks in advance!
Here is the output from windows power shell:
PS D:\misc\Code\python\mystuff> python .\CalculationTest.py
Please input a number:
>1
Please input a operator(i.e. + - * /):
>+
Please input another number:
>2
Adding 1 + 2 #why it shows these 4 lines?
Subtracting 1 - 2
Multiplying 1 * 2
Dividing 1 / 2
3
and here is my code:
class Calculation(object):
def add(self, a, b):
print "Adding %d + %d" % (a, b)
return a + b
def subtract(self, a, b):
print "Subtracting %d - %d" % (a, b)
return a - b
def multiply(self, a, b):
print "Multiplying %d * %d" % (a, b)
return a * b
def divide(self, a, b):
if b == 0:
print "Error"
exit(1)
else:
print "Dividing %d / %d" % (a, b)
return a / b
def get_result(self, a, b, operator):
operation = {
"+" : self.add(a, b), # I didn't mean to call these methods,
"-" : self.subtract(a, b), # but it seems that they ran.
"*" : self.multiply(a, b),
"/" : self.divide(a, b),
}
print operation[operator]
if __name__ == "__main__":
print "Please input a number:"
numA = int(raw_input(">"))
print "Please input a operator(i.e. + - * /):"
operator = raw_input(">")
print "Please input another number:"
numB = int(raw_input(">"))
calc = Calculation()
#print calc.add(numA, numB)
calc.get_result(numA, numB, operator)