I need to put a simple calculator to work. The program is running but I keeping the same numbers as number1 = 1
and number2 = 1
class Calculator:
def __init__(self, number1=1, number2=1):
self.number1 = number1
self.number2 = number2
def calculator(self):
operationDict = { "*": self.multiplication(), "/": self.division(), " ": self.sumOf(), "-": self.subtraction()}
while True:
self.number1 = int(input("Enter a digit, 0 to 9: "))
self.number2 = int(input("Enter another digit, 0 to 9: "))
print("number1 is: ", self.number1, " the number2 is: ", self.number2)
operation = input("Enter a ,-,/,*: ")
if operation == "*":
print(operationDict["*"])
if operation == "-":
print(operationDict["-"])
if operation == " ":
print(operationDict[" "])
if operation == "/":
print(operationDict["/"])
def sumOf(self):
osum = self.number1 self.number2
self.osum = osum
return osum
def subtraction(self):
osubs = self.number1 - self.number2
self.osubs = osubs
return osubs
def division(self):
odiv = self.number1 / self.number2
self.odiv = odiv
return round(odiv,2)
def multiplication(self):
omult = self.number1 * self.number2
self.omult = omult
return omult
oCalculator = Calculator()
oCalculator.calculator()
CodePudding user response:
You're calling your functions before you prompt for the numbers:
operationDict = { "*": self.multiplication(), "/": self.division(), " ": self.sumOf(), "-": self.subtraction()}
Instead put the functions themselves in the dict, and call them only after the numbers have been entered:
operationDict = { "*": self.multiplication, "/": self.division, " ": self.sumOf, "-": self.subtraction}
...
operation = input("Enter a ,-,/,*: ")
if operation == "*":
print(operationDict["*"]())
if operation == "-":
print(operationDict["-"]())
if operation == " ":
print(operationDict[" "]())
if operation == "/":
print(operationDict["/"]())
Note that the function gets called when the ()
operator is applied to it, so don't use ()
until you're ready to call the function!
The function can be written much more simply by avoiding the use of instance variables completely; instead just pass number1
and number2
directly to the operator functions. If you use operator functions that require arguments (rather than passing them implicitly as pre-initialized instance variables), it's impossible to accidentally call them before you have the argument values! And this lets you skip the step of defining your own wrapper functions; just use the built-in int.__add__
etc.
def calculator():
operation_dict = {
"*": int.__mul__,
"/": int.__truediv__,
" ": int.__add__,
"-": int.__sub__
}
while True:
number1 = int(input("Enter a digit, 0 to 9: "))
number2 = int(input("Enter another digit, 0 to 9: "))
print("number1 is: ", number1, " the number2 is: ", number2)
operation = input("Enter a ,-,/,*: ")
if operation in operation_dict:
print(operation_dict[operation](number1, number2))
CodePudding user response:
don't initialize the values of number1 and number2 as 1 in init method