-2

I have written a code that will add up the values in a tuple and calculate the average:

def average(values):
    return sum(values[0:]) / len(values[0:])

However, I get an unwanted floating point, like 2.0 instead of 2. How do I eliminate this, but still manage to get the correct average should the average not be an integer?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    You mean you want to convert the float to an integer [when it is a whole number](http://stackoverflow.com/questions/21583758/how-to-check-if-a-float-value-is-a-whole-number) or do you want to strip the decimal point and 0 when representing the number (say, when printing or writing it to a file)? – Martijn Pieters Sep 10 '14 at 16:23
  • This needs a fix in the code you use to display the numbers, not in the code you use for computation. (Also, the slices are pointless.) – user2357112 Sep 10 '14 at 16:24
  • I wish to convert the float to an integer when it is a whole number – user4027736 Sep 10 '14 at 16:25
  • Note that the `[0:]` slices are entirely redundant here; they only serve to create copies of the lists which you then discard again. Your code would perform better if you left those out altogether. – Martijn Pieters Sep 10 '14 at 16:25
  • 1
    @user4027736: why do you feel you need to have an integer value some of the time though? Is it because you don't want to see the `.0` when you output the number? What is the *reason* you think you need to do this? – Martijn Pieters Sep 10 '14 at 16:26
  • To remove the decimal separator and zero, see [Most Pythonic way to print \*at most\* some number of decimal places](http://stackoverflow.com/q/14997799) – Martijn Pieters Sep 10 '14 at 16:27
  • I don't want to see the .0, it looks clunky. – user4027736 Sep 10 '14 at 16:27
  • @user4027736: so you are doing this *when formatting the number for output*. – Martijn Pieters Sep 10 '14 at 16:28
  • Are you saying that 2.1 or even 2.32674673673 is okay, but if its 2.0, you'd rather just have 2? – tdelaney Sep 10 '14 at 16:34

1 Answers1

1

You may try like this:

if (yournumber).is_integer():
        print int(n)
else 
       print (n)
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331