本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于Python開發與大資料人工智能
前言
對于剛入門的Pythoner在學習程序中運行代碼是或多或少會遇到一些錯誤,剛開始可能看起來比較費勁,隨著代碼量的積累,熟能生巧當遇到一些運行時錯誤時能夠很快的定位問題原題,下面整理了常見的17個錯誤,希望能夠幫助到大家
1、
忘記在if,for,def,elif,else,class等宣告末尾加 :
會導致“SyntaxError :invalid syntax”如下:
if spam == 42
print('Hello!')
2、
使用= 而不是 ==
也會導致“SyntaxError: invalid syntax”
= 是賦值運算子而 == 是等于比較操作,該錯誤發生在如下代碼中:
if spam = 42:
print('Hello!')
3、
錯誤的使用縮進量
導致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”
記住縮進增加只用在以:結束的陳述句之后,而之后必須恢復到之前的縮進格式,該錯誤發生在如下代碼中:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
print('Howdy!')
4、
在 for 回圈陳述句中忘記呼叫 len()
導致“TypeError: 'list' object cannot be interpreted as an integer”
通常你想要通過索引來迭代一個list或者string的元素,這需要呼叫 range() 函式,要記得回傳len 值而不是回傳這個串列,
該錯誤發生在如下代碼中:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
5、
嘗試修改string的值
導致“TypeError: 'str' object does not support item assignment”
string是一種不可變的資料型別,該錯誤發生在如下代碼中:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
而正確做法是:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
6、
嘗試連接非字串值與字串
導致 “TypeError: Can't convert 'int' object to str implicitly”
該錯誤發生在如下代碼中:
numEggs = 12
print('I have ' + numEggs + ' eggs.')
而正確做法是:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
numEggs = 12
print('I have %s eggs.' % (numEggs))
7、
在字串首尾忘記加引號
導致“SyntaxError: EOL while scanning string literal”
該錯誤發生在如下代碼中:
print(Hello!')
print('Hello!)
myName = 'Al'
print('My name is ' + myName + . How are you?')
8、
變數或者函式名拼寫錯誤
導致“NameError: name 'fooba' is not defined”
該錯誤發生在如下代碼中:
foobar = 'Al'
print('My name is ' + fooba)
spam = ruond(4.2)
spam = Round(4.2)
9、
方法名拼寫錯誤
導致 “AttributeError: 'str' object has no attribute 'lowerr'”
該錯誤發生在如下代碼中:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10、
參考超過list最大索引
導致“IndexError: list index out of range”
該錯誤發生在如下代碼中:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/202421.html
標籤:其他

