Median - why is 2.0 needed here?


I was having the hardest time with this exercise until i changed ‘2’ to '2.0’
As far as i know python will give you a float if you divide using one slash, except when using two slashes, when it will round down, so why does adding .0 after the two makes a difference?

def median(get):
  sort_list = sorted(get)
  if len(get) % 2 == 0:
    index1 = len(sort_list) / 2 - 1
    index2 = len(sort_list) / 2
    med = sort_list[index1] + sort_list[index2] / 2.0 #This two right here, used to be an int
    return med
  elif len(sort_list) % 2 != 0:
    index = len(sort_list) // 2
    return sort_list[index]


this is true for python3, for python2 a division that involves two integers (9 / 2) will round down to the nearest integer, this does not happen when division involves a float (2.0)


I thought codecademy used python 3+ ? and also, what happens when it’s for example 5 / 2? 2.5 will round up or down? thanks for the help.


i said:

down is the keyword there, python floors the result, but if i say floor, it seems to confuse many people (especially non-native english speakers), so i switched to rounds down

well, its very simple to test:

import sys
print sys.version

but the fact that you can use print without parentheses should already tell you its python2. In python3, print is a function call, so it won’t work without parentheses


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.