439,932 Members | 1,908 Online
Need help? Post your question and get tips & solutions from a community of 439,932 IT Pros & Developers. It's quick & easy.

# Convert int to float

 P: n/a Hello I have this now: def gem(a): g = sum(a) / len(a) return g print gem([1,2,3,4]) print gem([1,10,100,1000]) print gem([1,-2,3,-4,5]) It now gives a int, but i would like to see floats. How can integrate that into the function? Regards, -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- Mar 15 '08 #1
7 Replies

 P: n/a On 2008-03-15, Guido van Brakel def gem(a): g = sum(a) / len(a) g = float(sum(a)) / len(a) > return g It now gives a int, but i would like to see floats. How can integrate that into the function? See above. Life is like a box of chocolates, you never know what you're gonna get sometimes it's a crunchy frog... -- Grant Mar 15 '08 #2

 P: n/a On 15 Mar, 22:43, Guido van Brakel

 P: n/a Grant Edwards wrote: On 2008-03-15, Guido van Brakel HelloI have this now: >>def gem(a): g = sum(a) / len(a) g = float(sum(a)) / len(a) >> return g Hi, Thank you very much,sometimes it is so amazing simple. Regards -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- Mar 15 '08 #4

 P: n/a On 15 Mar, 22:43, Guido van Brakel

 P: n/a On Mar 15, 4:43 pm, Guido van Brakel

 P: n/a On Mar 16, 4:43*am, Guido van Brakel

 P: n/a sturlamolden wrote: Guido van Brakel wrote: >>def gem(a): g = sum(a) / len(a) return g >It now gives a int, but i would like to see floats. How can integratethat into the function? You get an int because you are doing integer division. Cast one int to float. def gem(a): g = sum(a) / float(len(a)) return g An alternative is to multiply by 1.0. def gem(a): g = 1.0 * sum(a) / len(a) return g The gem function is well-defined on sequences of complex numbers, in which case the float() method will raise a TypeError, while the 1.0* method will return the complex result. It may not be what van Brakel wants here, but it's an alternative to keep in mind. And I find it easier to type. -- --Bryan Mar 17 '08 #8

### This discussion thread is closed

Replies have been disabled for this discussion.