gpt4 book ai didi

python - (python) 语法错误 : invalid syntax in def function

转载 作者:行者123 更新时间:2023-11-30 23:02:02 25 4
gpt4 key购买 nike

  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”都有一个错误。我还查看了之前有关此错误的每个问题。据我了解,缩进是正确的。请帮忙,这是我第一次收到这样的错误。 (遵循一本书的代码)

最佳答案

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

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

关于python - (python) 语法错误 : invalid syntax in def function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com