Design a Program to evaluate simple expressions in Python

So, guys today we will learn How to design a Program to evaluate simple expressions in Python. Let’s do it together. We are basically supposed to evaluate the simple expressions in Python. Given expression is in the form of string. Expressions are representations of value.

We are going to use arithmetic operators.

Program to evaluate simple expressions in Python

I hope you guys know what is BODMAS rule, no need to worry if it is not followed. (Bodmas stands for “brackets, orders, division, multiplication, addition, subtraction”.)

For E.g.

  • 3*2-1.

Ans= 5

  • 4/2-1

Ans= 1

We will be evaluating the expression from left to right and not on the basis of the precedence rule. The only thing we need to calculate is simple expressions. That’s it. If the syntax of the expression is incorrect then will simply pass on a message saying  “Expression is Invalid”.

Code:

def digits(n): 

  return (n >= '0' and n <= '9'); 

def val(n): 
  return ord(n) - ord('0'); 

def solve(q): 

  l1 = len(q); 
  
  if (l1 == 0): 
    return -1; 

  ans = val(q[0]); 

  for i in range(1,l1,2):
    o1 = q[i]; 
    o2 = q[i + 1]; 

  
    if (solve(o2)==False): 
      return -1; 

  
    if (o1 == '+'): 
      ans += val(o2); 
    elif (o1 == '-'): 
      ans -= int(val(o2)); 
    elif (o1 == '*'): 
      ans *= int(val(o2)); 
    elif (o1 == '/'): 
      ans /= int(val(o2)); 

    
    else: 
      return -1; 
  
  return ans; 


q1 = "4*5/2+10-5"; 
ans = solve(q1); 
print(q1,"is Invalid") if (ans == -1) else print("Answer of",q1,"is",ans); 

q2 = "9-5*1"; 
ans = solve(q2); 
print(q2,"is Invalid") if (ans == -1) else print("Answer of",q2,"is",ans); 


Output:

4*5/2+10-5 is Invalid                                                                                                                                                              

Answer of 9-5*1 is 4

Want to learn more have a look! So last but not least Keep Learning, Keep Coding!
Find the GCD of two numbers recursively in Python

Find indices of the non-zero elements in the Python list

Leave a Reply

Your email address will not be published.