eval is a built-in-function used in python, eval function parses the expression passed to it and evaluates it as a python expression. Once this expression has been evaluated the value is returned. The eval function is typically used to evaluate mathematical functions.

Syntax

Keep in mind that the expression passed to this function must be in String format.

eval(expression)

Most often, the result will be an integer, however in some expressions expect to see decimal values returned.


Evaluating mathematical Expressions

As you can see, the python eval function can evaluate several types of expressions and return the answer in the appropriate data type.

>>> eval('2+2')
4
>>> eval('2*7')
14
>>> eval('5/2')
2.5

Combining eval with input

The Python input function takes from the user input, and returns it into a string format. This makes it perfect for the eval function which only takes strings as input.

user_inp = input("Enter valid expression: ")
result = eval(user_inp)
print(result)

Let’s try inserting some expressions into the above code and displaying their output.

Enter valid expression: 2 ** 3
8
Enter valid expression: 4 * 10
40
Enter valid expression: 2 + 3 - 6 / 4
3.5

The interesting thing to notice is that the eval function obeys the rules of BODMAS. In the last example, it first evaluated 6/4 then subtracted it from 2 + 3.


Calculating expressions with unknowns

Contrary to what many might think, you can evaluate expressions with unknowns as well. Of course, you’ll need a value for the unknown before finally executing it.

user_inp = input("Enter valid expression: ")
x = int(input("Value of x: "))

result = eval(user_inp)
print(result)

Remember, x must be an integer value. Which is why we convert it using the int function after taking input from the user.

Enter valid expression: x + 9
Value of x: 2
11

Of course, you can repeat this with two or more unknowns as well. The sky is the limit.

Congratulations, you have now made your very own expression solver. Try taking things a step further and using other functions to evaluate more complicated expressions.


This marks the end of the Python eval function section. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions be can be directed to the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments