Compute a Mathematical Expression String in Python
Hello friends, do you like solving large mathematical expressions? Not me either, but we can use Python to compute mathematical expression strings for you. In this tutorial, you will learn how to evaluate a mathematical expression that is entered as a string.
Compute a Mathematical Expression String in Python
In this tutorial, I will tell you two ways of solving this task.
- String Manipulation.
- eval() function.
1 . String Manipulation
The first hurdle while evaluating a mathematical expression string is to remove the whitespaces amongst the expression. I have used a for loop to iterate over the characters of the string. If the particular character is not a whitespace I have added it to a list, l
. To check if the character is whitespace or not, I have used the isspace() function. Now let’s define a function, calc
which takes two operands and an operand, num1, num2, and op
respectively as parameters. Check if the operand op
is a +, -, *, /, or **
calculate the result
accordingly and return it.
Code :
myStr = "5* 3 / 5+1" l = [] for i in myStr: if not i.isspace(): l.append(i) def calc(num1 , num2, op): if op == '+': result = num1 + num2 elif op == '-': result = num1 - num2 elif op == '*': result = num1 * num2 elif op == '/': result = num1 / num2 elif op == '^': result = num1 ** num2 else: print("Invalid") return result for i in range(1, len(l), 2): num1 = int(l[i-1]) num2 = int(l[i+1]) result = calc(num1, num2, l[i]) l[i+1] = result print(result)
Output :
4
I have used a for loop with starting value 1, end value as the length of the list, and skip value 2. This provides me with the operands present in the expression. Now I have defined the two operands by type-casting the value at (i-1)
th position of the list as num1
and (i+1)
th position of the list as num2
. Pass these values to the function calc. I have stored the function’s returned value in a temporary variable result
and overwrote it with the character at the list’s (i+1)
position. Finally, print the result
variable.
However, this piece of code ensures computing the correct answer of the mathematical expression but it is incapable of following the BODMAS rule.
Input :
myStr = "5+ 9 / 3 +1"
Output :
5
2. eval() function
You can also compute a mathematical expression string using the eval()
function. I took an expression in a temporary variable myStr and passed it to the eval() function. This method follows the BODMAS rule and computes accordingly.
Code :
myStr = eval("5+ 9 / 3 +1") print(myStr)
Output :
9.0
This function overlooks the whitespaces in the expression string.
Now you can compute a mathematical expression string in Python.
Leave a Reply