(python)def函数语法无效

时间:2016-01-09 03:25:26

标签: python

  File "stats0.py", line 40
    def median(numbers):
      ^
  SyntaxError: invalid syntax
def median(numbers):
    numbers.sort()
    size = len(numbers)
    midPos = size/2
    if size%2==0:
        median = (numbers[midPos]+numbers[midPos-1])/2.0
    else:
        median = numbers[midPos]
    return median

我一直收到这个错误。我试过评论它但每个'def'都有错误。我确实看过以前关于这个问题的每个问题。据我所知,我的缩进是正确的。请帮忙,这是我第一次收到这样的错误。 (遵循书中的代码)

1 个答案:

答案 0 :(得分:3)

错误将在函数定义之前。在您的功能之前是否定义了任何代码。我能够获得上述程序的输出。 下面给出了可执行代码供您参考。

def median(numbers):
    numbers.sort()
    size = len(numbers)
    midPos = size/2
    if size%2==0:
        median = (numbers[midPos]+numbers[midPos-1])/2.0
    else:
        median = numbers[midPos]
    return median


if __name__ == "__main__":

    numbers = [1,2,3,4,5,6,7,8,9,10]
    print median(numbers)

Output Console:

5.5

Process finished with exit code 0