Alexander Smith
Alexander Smith

Reputation: 65

Round function isn't rounding?

I'm trying to create a basic mean function that will allow the user to enter a list of integers and return the mean of the dataset. One of the caveats is the program should allow the user to select how many decimals they want the answer rounded to.

The code snippet below is what is inside my mean() function, which takes a list of numbers as a parameter.

For example, if I enter [5, 3, 3, 2] and want to round to 2 decimals, which should be 3.25, the program returns 3.0.

sum = 0
for item in lst:
    sum += item

mean = round(float(sum / len(lst)), decimals)

print mean

Upvotes: 2

Views: 68

Answers (1)

Olivier Melançon
Olivier Melançon

Reputation: 22294

Using / in Python2 will do an integer division if both arguments are integers. Thus, you want to cast sum to a float.

mean = round(float(sum) / len(lst), decimals)

Although, let me point out that you should not be using sum as a variable name as it overwrites the sum builtin. In fact, you should actually be using the sum builtin.

lst = [1, 2, 4]

mean = round(float(sum(lst)) / len(lst), 2)

print (mean)  # 2.33

Upvotes: 5

Related Questions