Skip to content

module17_異常處理_example3.py輸出結果問題 #185

Answered by benctw
EricAgumonJou asked this question in Q&A
Discussion options

You must be logged in to vote

NameError的原因可參考:https://docs.python.org/zh-tw/3/library/exceptions.html#NameError
觸發原因為:找不到該名稱的區域變數或全域變數

3x不可能是變數名稱,所以不會觸發NameError例外,但又因為語法不完整,所以觸發SyntaxError錯誤
x3有可能是變數名稱,但是找不到這個變數,所以觸發NameError例外

以上不管是哪一種錯誤或例外,都可以用try ... except ...捕捉錯誤,進行容錯處理。

SyntaxError: unexpected EOF while parsing:解析(語法)時,出現了未預期的檔案結尾(End of File)
若在Jupyter Notebook輸入以下語法也會出現相同錯誤,我認為3x不可能會是變數,然而又不能正確描述此語法,所以SyntaxError

Python官方文件說明:https://docs.python.org/zh-tw/3/tutorial/errors.html

常見的(至少)兩種不同的錯誤類別為:語法錯誤 (syntax error) 和例外 (exception)。

語法錯誤 (Syntax Error)

語法錯誤又稱剖析錯誤 (parsing error),它或許是學習 Python 的過程最常聽見的抱怨:

>>>
>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
   …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@EricAgumonJou
Comment options

Answer selected by EricAgumonJou
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants