我编写了我的程序来从命令行中获取参数并使用文件中的数字来生成一堆统计信息。由于存在缩进错误,我无法编译代码。我试过但我只是不知道我的缩进不正确。有人能指出我正确的方向。
代码:
import sys
def median(alist):
n=len(alist)
if n<1:
return 'There are none'
if n%2:
return sorted(alist)[n//2]
else:
return sum(sorted(alist)[n//2-1:n//2+1])/2.0
def minimum(alist):
return min(alist)
def maximum(alist):
return max(alist)
def average(alist):
return sum(alist) / len(alist)
def main():
with open(sys.argv[1], 'r') as handle:
lines = handle.readlines()
list1 = []
for line in lines:
fields = line.split()
for field in fields:
list1.append(float(field))
median(alist)
minimum(alist)
maximum(alist)
average(alist)
if __name__ == '__main__':
main()
错误:
文件&#34; stats.py&#34;,第23行 lines = handle.readlines()
^
IndentationError:预期缩进块
答案 0 :(得分:1)
您的代码需要在with
语句后缩进。这是正确的代码。
import sys
def median(alist):
n=len(alist)
if n<1:
return 'There are none'
if n%2:
return sorted(alist)[n//2]
else:
return sum(sorted(alist)[n//2-1:n//2+1])/2.0
def minimum(alist):
return min(alist)
def maximum(alist):
return max(alist)
def average(alist):
return sum(alist) / len(alist)
def main():
with open(sys.argv[1], 'r') as handle:
lines = handle.readlines()
list1 = []
for line in lines:
fields = line.split()
for field in fields:
list1.append(float(field))
median(alist)
minimum(alist)
maximum(alist)
average(alist)
if __name__ == '__main__':
main()
答案 1 :(得分:0)
您的缩进应该与脚本一致 Pep 8强烈建议在标签上使用空格。 我个人使用4个空格
正如JonDoe上面所说的那样,在with语句之后的缩进需要缩进,而if语句