#54780: python解


liu_owo_tw (liu ouo tw)


錯誤有三種:

unexpected indent:某行縮排比外層還深但前一行不是冒號行

expected an indented block:某行是冒號行但下一行卻沒有更深的縮排

unindent does not match any outer indentation level:縮排減少時,沒有對齊到任何外層合法的縮排層級

 

用一個stack來記錄目前合法的縮排層級

初始值是[0],代表最外層縮排,每遇到冒號行,下一行必須比當前層級更深,並把該縮排層級push進stack

當縮排減少時,逐層pop,直到找到一個小於等於當前縮排的層級

 

邏輯為:

  1. 計算縮排數
  2. 檢查是否為冒號行:如果是,下一行必須更深,否則報 expected an indented block
  3. 檢查 unexpected indent:若當前行縮排比最內層深,但上一行不是冒號行 → 報錯
  4. 處理 unindent:若縮排比最內層淺,逐層 pop,若最後不等於任何層級 → 報 unindent does not match any outer indentation level
  5. 更新狀態:記錄當前行是否為冒號行,讓下一行判斷

 

程式碼:點我看程式碼

#54781: Re: python解


liu_owo_tw (liu ouo tw)