1. 程式人生 > 實用技巧 >IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level

# Author kevin_hou

def sanitize(time_string):  #格式化時間
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return (time_string)
    (mins, secs) = time_string.split(splitter)
    return (mins + '.' + secs)

class AthleteList(list):  #定義類
    def __init__(self, a_name, a_dob=None, a_times=[]):
        list.__init__([])
        self.name = a_name
        self.dob = a_dob
        self.extend(a_times)
    def top3(self):  #定義排在前3的函式
        return (sorted(set([sanitize(t) for t in self]))[0:3])

def get_coach_data(filename):  #開啟檔案獲取資料
    try:
        with open(filename) as f:
            data = f.readline()
            temp1 = data.strip().split(',')
            return (AthleteList(temp1.pop(0), temp1.pop(0), temp1))
    except IOError as ioerr:
        print('File error:' + str(ioerr))
        return(None)

   james = get_coach_data('james2.txt')
   sarah = get_coach_data('sarah2.txt')

print(james.name +" 's fastest times are:" + str(james.top3()))
#James Lee 's fastest times are:[' 2.34', '2.01', '2.22']
print(sarah.name +" 's fastest times are: " + str(sarah.top3()))
#Sarah Sweeney 's fastest times are: ['2.18', '2.25', '2.39']

  

出現這個錯誤的原因是115,116行程式碼起始位置存在空格,只要將相應的空格去除就OK了。這裡強調一下,python的程式碼對齊要求比較嚴格,如果書寫有誤,會自動檢查出,並提示此錯誤。

去掉空格執行正常,輸出正常。有時候不是程式碼邏輯輸入錯誤,而是格式或對齊方式輸入錯誤導致程式碼執行出錯。