-2

How can I make this function return and print a float:

x = input ("Enter 5 numbers:")

def average(x):
       return sum(x) / len(x)

print average(x)
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
  • take a look here: http://stackoverflow.com/search?q=python+division+float – kratenko Jul 01 '14 at 14:49
  • @LasseV.Karlsen: Right, but he's on Python 2 apparently and should be using `raw_input()`. – Tim Pietzcker Jul 01 '14 at 14:50
  • @Bakuriu: That "duplicate" is a long way away from helping him in this situation. – Tim Pietzcker Jul 01 '14 at 14:51
  • 1
    @TimPietzcker I don't see your point. Note that using `input` the `x` in his code is a list/tuple of numbers so the **only** problem he has (and that ha also has asked explicitly) is how to do floating point arithmetic when the input are integers. And that's *exactly* what the duplicate question is about. – Bakuriu Jul 01 '14 at 14:53
  • 1
    So since he's on Python 2, then I was wrong above about what he asked about. The only thing left then is the float conversion, so the duplicate should be fine then. – Lasse V. Karlsen Jul 01 '14 at 14:53
  • @Bakuriu thanks, the duplicate question solves my problem perfectly! I appreciate it very much! – Joe T. Boka Jul 01 '14 at 15:08

1 Answers1

1

In python 2.x, int object divided by int yields int.

You should convert one (or both) of the operand to float to get float result:

>>> 10 / 2
5
>>> float(10) / 2
5.0

Or turn on true division using __future__ module:

>>> from __future__ import division
>>> 10 / 2
5.0
falsetru
  • 357,413
  • 63
  • 732
  • 636