I am trying to make calculator that can solve expressions with basic 4 operators, like 1+2*3-4/5, however it does not work and I do not know what is wrong. Please check my code.
The main thing you are doing wrong is that you are checking the value of c rather that the partitioned operator. You can also unpack the result from s.partition to make things a little easier by using left and right for the actual operations.
def ret(s):
s = str(s)
if s.isdigit():
return float(s)
for c in ('-','+','*','/'):
left, op, right = s.partition(c)
if op == '*':
return ret(left) * ret(right)
elif op == '/':
return ret(left) / ret(right)
elif op == '+':
return ret(left) + ret(right)
elif op == '-':
return ret(left) - ret(right)
print(ret('1+2'))
Also, you will need to reverse the order of your operations as you want to first do addition and subtraction, followed by multiplication and division.
What I mean is, if you have an expression like 4+4*3, you want to divide it into
ret(4) + ret(4 * 3)
Since it is a recursive call, you want the operators with the highest precedence to be the last on the call stack so they are executed first when the function returns.
As an example:
print(ret('1+2*6'))
print(ret('3*8+6/2'))
OUTPUT
13.0
27.0