NiceCoder
NiceCoder

Reputation: 19

Why Pythons eval() mistakes?

I need to solve some mathematical equations, something like below (but each time different formula):

formula="(2/10^8*x^2)+0.0131*x-1017.3-30"

where x is an integer.

I used eval() function to solve the problem. Function gave me an exception of:

TypeError: unsupported operand type(s) for ^: 'float' and 'int'

I solved it like this:

formula=formula.replace('^','**') 

Now, I encountered with another problem.

eval("2/10") 

returns 0 instead I need 0.2, as a result I get a wrong outcome. I appreciate for any answer.

Upvotes: 0

Views: 91

Answers (1)

Zaur Nasibov
Zaur Nasibov

Reputation: 22659

Well, in Python 2.x int / int always returns an integer. Use Python 3 or explicitly write one of the arguments as a float, e.g. 2.0 / 10, or (as Marjin Pieters reminds us), import the explicit Py3-like division behaviour as: from __future__ import division.

Upvotes: 3

Related Questions