2017-09-13 82 views
-4

我寫過我的程序從命令行獲取參數並使用文件中的數字生成一堆統計數據。由於存在縮進錯誤,我無法編譯我的代碼。我試過了,但我只是看不到我的縮進不正確。有人能指出我正確的方向嗎?我的代碼的縮進

代碼:

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() 

錯誤:需要後with語句縮進

File "stats.py", line 23
lines = handle.readlines()
^
IndentationError: expected an indented block

+2

查看錯誤。它字面上*告訴你*你的代碼出錯的地方。 – Jerrybibo

+0

'lines = handle.readlines()'之前需要額外的空間。 – DyZ

回答

1

您的代碼。這是正確的代碼。

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() 
+2

你的縮進是有爭議的。只有'lines = handle.readlines()'必須縮進。以下所有行在'with'塊中都沒有業務。 – DyZ

+1

你是對的。我會解決它。 – JohnDoe

0

您縮進應該是一致的,雖然出腳本 佩普8強recomends標籤上使用的空間。 我個人使用4個空格

由於JonDoe已經縮進上面說的與語句需要爲做縮進,而之後,if語句