Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate expression as float in Python

Tags:

python

I want to write a function which inputs two variables a, b and which returns a/b as a float irrespective of the types of a and b. Right now I'm doing this as:

def f(a, b):
    return float(a)/float(b)

Is there a better way to do this?

like image 451
Bernhard Heijstek Avatar asked Dec 06 '25 10:12

Bernhard Heijstek


1 Answers

Assuming you are using Python2, put this at the top of the file

from __future__ import division

now / will always give a float. Use // for the old behaviour.

If you are using Python3, then this is already the default behaviour of /

like image 87
John La Rooy Avatar answered Dec 12 '25 12:12

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!