Python常見錯誤

2021-10-12 18:21:06 字數 2043 閱讀 5944

在剛學習 python 程式設計時,經常會看到一些報錯資訊,下面是一些常見易犯的錯誤

python 的語法錯誤或者稱之為解析錯,是初學者經常碰到的,如下例項

while

true

print

('hello world'

)file ""

, line 1

,in ?

while

true

print

('hello world')^

syntaxerror: invalid syntax

這個例子中,函式 print() 被檢查到有錯誤,是它前面缺少了乙個冒號 : 。

語法分析器指出了出錯的一行,並且在最先找到的錯誤的位置標記了乙個小小的箭頭。

python預設的縮排為四個空格,通常我們使用一次tab來控制縮排,以防止空格輸出混亂

while

true :

print

('hello world'

) file ""

, line 1

while

true :

^syntaxerror: invalid character in identifier

未使用縮排

str=[

'a',

'b',

'c']

;for name in str1:

print

(name)

file ""

, line 3

print

(name)

^indentationerror: expected an indented block

while

true

: a

break

traceback (most recent call last)

: file ""

, line 3,in

anameerror: name 'a'

isnot defined

a =

'2'+

2traceback (most recent call last)

: file ""

, line 1,in

a ='2'+

2typeerror: can only concatenate str

(not

"int"

) to str

元組是不可變型別,不可對元素進行修改,但如果元素是可變型別(列表,字典等)可對內容進行修改

a =

('a'

,'b'

,'c')a[

0]='d'

traceback (most recent call last)

: file ""

, line 2,in

a[0]

='d'

typeerror:

'tuple'

object does not support item assignment

由於某些庫在不斷更新,可能會導致版本之間互相不相容,需要使用合適的庫版本來搭建程式

from collections import iterator

deprecationwarning: using or importing the abcs from

'collections' instead of from

'collections.abc'

is deprecated,

andin

3.8 it will stop working

from collections import iterator

出現錯誤時,終端或者pycharm的terminal終端中會出現報錯資訊,翻譯報錯資訊通常可以使我們定位出現錯誤的位置及直接原因,根據提示來一步步修改至可以正常執行程式即可

Python常見錯誤

1.indentationerror expected an indented block python語言是一款對縮排非常敏感的語言,給很多初學者帶來了困惑,即便是很有經驗的python程式設計師,也可能陷入陷阱當中。最常見的情況是tab和空格的混用會導致錯誤,或者縮排不對,而這是用肉眼無法分別的...

python 常見錯誤

原因 pylint 未安裝 配置正確 解決 pip show pylint 看看版本 settings.json 設定成這樣就好了 python.linting.pylintpath pylint python.pythonpath usr bin python3 使用vscode開發python程...

python常見錯誤

安裝python之後,有時候需檢查python和pip是否安裝成功。在命令列中,輸入python,會反饋當前系統預設的python版本資訊。如果在輸入完python之後,就行輸入pip。則會出現如下列印錯誤 pip traceback most recent call last file line ...