I'm making a calculator for a class assignment and my program works but I want it to be more efficient / well designed. I'd like to be able to create a 'template' function for a calculation but right now my code is quite linear in that I've repeated the 'calculating' segments to account for every possible equation. So far my program allows for up to 3 numbers and 2 operators. Here's my code:
if operator1 == "+":
if operator2 == "+":
prevInput = (num1 + num2 + num3)
elif operator2 == "-":
prevInput = (num1 + num2 - num3)
elif operator2 == "/":
prevInput = (num1 + (num2 / num3))
elif operator2 == "x" or operator2 == "*":
prevInput = (num1 + (num2 * num3))
elif operator1 == "-":
if operator2 == "+":
prevInput = (num1 - num2 + num3)
elif operator2 == "-":
prevInput = (num1 - num2 - num3)
elif operator2 == "/":
prevInput = (num1 - (num2 / num3))
elif operator2 == "x" or operator2 == "*":
prevInput = (num1 - (num2 * num3))
elif operator1 == "/":
if operator2 == "+":
prevInput = ((num1 / num2) + num3)
elif operator2 == "-":
prevInput = ((num1 / num2) - num3)
elif operator2 == "/":
prevInput = (num1 / (num2 / num3))
elif operator2 == "x" or operator2 == "*":
prevInput = (num1 / (num2 * num3))
elif operator1 == "x" or operator1 == "*":
if operator2 == "+":
prevInput = ((num1 * num2) + num3)
elif operator2 == "-":
prevInput = ((num1 * num2) - num3)
elif operator2 == "/":
prevInput = (num1 * (num2 / num3))
elif operator2 == "x" or operator2 == "*":
prevInput = (num1 * (num2 * num3))
elif not(num2 == ""):
num1, num2 = float(num1), float(num2)
if operator1 == "+":
prevInput = (num1 + num2)
elif operator1 == "-":
prevInput = (num1 - num2)
elif operator1 == "/":
prevInput = (num1 / num2)
elif operator1 == "x" or operator1 == "*":
prevInput = (num1 * num2)
FYI this part is within a function itself and the prevInput variable is printed at the end of the function, but I believe the embedding of another function could be utilised in this case. Any suggestions with how I could create a default calculation template? or am I stuck with my linear format? Sorry if this seems simple, I'm only a freshman in CS.