I want a fully functioning calculator where you put in things like 1+2
or 1*2
or 1+a
or 1*a
, that sort of thing. However I am having some trouble when combining +
and *
. Any ideas how I could improve it?
What I have so far (sorry about the messy and unnecessary conversions from str to int and back):
class Math:
def Calculate(stuff):
result = 0
resultstr = ""
if "*" in stuff:
y = stuff.split("*")
for x in y:
if result == 0:
result = x
else:
try:
x = int(x)
except:
result = str(result) + x
result = result.replace("0*", "")
result = result.replace("*0", "")
else:
try:
result = int(result) * int(x)
except:
resultstr = str(result)
result = x
if "+" in stuff:
y = stuff.split("+")
for x in y:
try:
x = int(x)
except:
result = str(result) + "+" + x
result = result.replace("0+", "")
result = result.replace("+0", "")
else:
try:
result = int(result) + int(x)
except:
resultstr = str(result) + "+"
result = x
finalresult = str(resultstr)+str(result)
print(str(finalresult))
h = Math
h.Calculate("a*5+5")