搜尋
首頁後端開發Python教學python中一些常見的錯誤

python中一些常見的錯誤

Jun 16, 2020 pm 03:53 PM
python

python中一些常見的錯誤

python中常見的錯誤:

0、忘記寫冒號

在if、elif、else、for、while、class、def 語句後面忘記加「:」

if spam == 42
    print('Hello!')

導致:SyntaxError: invalid syntax

2、使用錯誤的縮排

Python用縮排區分程式碼區塊,常見的錯誤用法:

print('Hello!')
    print('Howdy!')

導致:IndentationError: unexpected indent。同一個程式碼區塊中的每行程式碼都必須保持一致的縮排量

if spam == 42:
    print('Hello!')
  print('Howdy!')

導致:IndentationError: unindent does not match any outer indentation level。程式碼區塊結束後縮排恢復到原來的位置

if spam == 42:
print('Hello!')

導致:IndentationError: expected an indented block,“:” 後面要使用縮排

#3、變數沒有定義

if spam == 42:
    print('Hello!')

導致:NameError: name 'spam' is not defined

4、取得清單元素索引位置忘記呼叫len 方法

透過索引位置取得元素的時候,忘記使用len 函式取得列表的長度。

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
    print(spam[i])

導致:TypeError: range() integer end argument expected, got list.
正確的做法是:

spam = ['cat', 'dog', 'mouse']
for i in range(len(spam)):
    print(spam[i])

當然,更Pythonic 的寫法是用enumerate

spam = ['cat', 'dog', 'mouse']
for i, item in enumerate(spam):
    print(i, item)

5、修改字串

字串一個序列對象,支援用索引取得元素,但它和列表對像不同,字串是不可變對象,不支援修改。

spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)

導致:TypeError: 'str' object does not support item assignment

正確地做法應該是:

spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)

6、字串與非字串連接

num_eggs = 12
print('I have ' + num_eggs + ' eggs.')

導致:TypeError: cannot concatenate 'str' and 'int' objects

字串與非字串連接時,必須把非字串物件強制轉換為字串類型

num_eggs = 12
print('I have ' + str(num_eggs) + ' eggs.')

或使用字串的格式化形式

num_eggs = 12
print('I have %s eggs.' % (num_eggs))

7、使用錯誤的索引位置

spam = ['cat', 'dog', 'mouse']
print(spam[3])

導致:IndexError: list index out of range

#列表物件的索引是從0開始的,第3個元素應該是使用spam[2] 存取

8、字典中使用不存在的鍵

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

在字典物件中存取key 可以使用 [ ],但是如果該key 不存在,就會導致:KeyError: 'zebra'

正確的方式應該使用get 方法

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam.get('zebra'))

key 不存在時,get 預設傳回None

9、用關鍵字做變數名稱

class = 'algebra'

導致:SyntaxError: invalid syntax

在Python 中不允許使用關鍵字作為變數名稱。 Python3 共有33個關鍵字。

>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

10、函數中局部變數賦值前被使用

someVar = 42

def myFunction():
    print(someVar)
    someVar = 100

myFunction()

導致:UnboundLocalError: local variable 'someVar' referenced before assignment

當函數中有一個與全域作用當域中同名的變數時,它會按照LEGB 的順序查找該變量,如果在函數內部的局部作用域中也定義了一個同名的變量,那麼就不再到外部作用域查找了。

因此,在myFunction 函數中someVar 被定義了,所以print(someVar) 就不再外面查找了,但是print 的時候該變數還沒賦值,所以出現了UnboundLocalError

#11 、使用自增「 」 自減「--」

spam = 0
spam++

哈哈,Python 中沒有自增自減操作符,如果你是從C、Java轉過來的話,你可要注意了。你可以使用「 =」 來取代「 」

spam = 0
spam += 1

12、錯誤地呼叫類別中的方法

class Foo:
    def method1():
        print('m1')
    def method2(self):
        print("m2")

a = Foo()
a.method1()

導致:TypeError: method1() takes 0 positional arguments but 1 was given

method1 是Foo 類別的一個成員方法,該方法不接受任何參數,調用a.method1() 相當於調用Foo.method1(a),但method1 不接受任何參數,所以報錯了。正確的呼叫方式應該是 Foo.method1()。

更多相關知識請關注python影片教學欄位

以上是python中一些常見的錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:juejin。如有侵權,請聯絡admin@php.cn刪除
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境