15. Median


15. Median

File "python", line 10
SyntaxError: invalid syntax

This should work except I can't find the syntax error.

def median(lst):
    median_answer = 0
    new = sorted(lst)
    if len(new) % 2 ==0:
        median_answer = (new[(len(new)/2)-1] + new[(len(new)/2)]/2.0 
        median_answer = new[len(new)/2]    
    return median_answer


look at the line above the error message, pay special attention to the parentheses.


In other words, Check your syntax on this line:

median_answer = (new[(len(new)/2)-1] + new[(len(new)/2)]/2.0


Ahh. So to find the syntax error you look at the line above? I was looking at the else line "else:" and was confused. Many thanks.


the thing is parentheses allow us to put the code on multiply lines:

"hello world"

So python expected you continue with the code, which you didn't. You introduced else, which it wasn't expecting


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