[Python學習]錯誤篇一:SyntaxError: invalid syntax & IndentationError: expected an indented block


REFERENCE:《Head First Python》

ID:我的第一篇[Python學習]

BIRTHDAY:2019.7.6

EXPERIENCE_SHARING:兩個程序錯誤類型

 

1、錯誤類型:

>>> for each_item in movies:
    if isinstance(each_items,list):
    for nested_item in each_item: 
        print(nested_item)
    else:
        print(each_item)
        
SyntaxError: invalid syntax
>>> 

 SyntaxError: invalid syntax

意思就是“語法錯誤:不正確的語法”

一般是格式上漏掉或者多了些東西。或者字符格式不對。

(1)錯誤原因:

第二行的 each_items多了一個s

修改后:

>>> for each_item in movies:
    if isinstance(each_item,list)
    for nested_item in each_item:
        print(nested_item)
    else:
        print(each_item)
        
SyntaxError: invalid syntax

 (2)錯誤原因

第二行的冒號似乎和第三行的不一樣,可能是中文狀態下的冒號。修改試試:

>>> for each_item in movies:
    if isinstance(each_item,list):
    for nested_item in each_item:
        print(nested_item)
    else:
        print(each_item)
        
  File "<pyshell#18>", line 3
    for nested_item in each_item:
      ^
IndentationError: expected an indented block
>>> 

 出現新的錯誤類型:

IndentationError: expected an indented block

參考下方第二個錯誤類型的解決方法:

2、錯誤類型:

 

>>> for each_item in movies:
    if isinstance(each_item,list):
    for nested_item in each_item:                                                                                                                                    
print(nested_item) else: print(each_item) File "<pyshell#13>", line 3 for nested_item in each_item:
print(nested_item) ^ IndentationError: expected an indented block
>>>

IndentationError: expected an indented block

說明此處需要縮進,你只要在出現錯誤的那一行,按空格或Tab(但不能混用)鍵縮進就行。

一句話 有冒號的下一行往往要縮進。

 

 Python語言是一款對縮進非常敏感的語言,給很多初學者帶來不少困惑,即便是很有經驗的python程序員,也可能陷入陷阱當中。

最常見的情況是tab和空格的混用會導致錯誤,或者縮進不對,而這是用肉眼無法分別的。

(參考 知乎·回答)

 

第三行縮進后:

>>> for each_item in movies:
    if isinstance(each_item,list):
          for nested_item in each_item:                                                                                                                                    print(nested_item)
    else:
        print(each_item)

        
A
B
C
1
2
3
HAPPY
['sadness', 'sorrow', 'moved']
>>>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM