1)忘記在 if , elif , else , for , while , class ,def 聲明末尾添加 :(導(dǎo)致 “SyntaxError :invalid syntax”)
該錯(cuò)誤將發(fā)生在類似如下代碼中:
if spam== 42 print('Hello!')
2) 使用 = 而不是 ==(導(dǎo)致“SyntaxError: invalid syntax”)
= 是賦值操作符而 == 是等于比較操作。該錯(cuò)誤發(fā)生在如下代碼中:
if spam= 42: print('Hello!')
3)錯(cuò)誤的使用縮進(jìn)量。(導(dǎo)致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)
記住縮進(jìn)增加只用在以:結(jié)束的語句之后,而之后必須恢復(fù)到之前的縮進(jìn)格式。該錯(cuò)誤發(fā)生在如下代碼中:
print('Hello!') print('Howdy!') 或者: if spam== 42: print('Hello!') print('Howdy!') 或者: if spam== 42:print('Hello!')
4)在 for 循環(huán)語句中忘記調(diào)用 len() (導(dǎo)致“TypeError: 'list' object cannot be interpreted as an integer”)
通常你想要通過索引來迭代一個(gè)list或者string的元素,這需要調(diào)用 range() 函數(shù)。要記得返回len 值而不是返回這個(gè)列表。
該錯(cuò)誤發(fā)生在如下代碼中:
spam= ['cat','dog','mouse']for iin range(spam): print(spam[i])
5)嘗試修改string的值(導(dǎo)致“TypeError: 'str' object does not support item assignment”)
string是一種不可變的數(shù)據(jù)類型,該錯(cuò)誤發(fā)生在如下代碼中:
spam= 'I have a pet cat.'spam[13]= 'r'print(spam)
而你實(shí)際想要這樣做:
spam= 'I have a pet cat.'spam= spam[:13]+ 'r' + spam[14:]print(spam)
6)嘗試連接非字符串值與字符串(導(dǎo)致 “TypeError: Can't convert 'int' object to str implicitly”)
該錯(cuò)誤發(fā)生在如下代碼中:
numEggs= 12print('I have ' + numEggs+ ' eggs.')
而你實(shí)際想要這樣做:
numEggs= 12print('I have ' + str(numEggs)+ ' eggs.') 或者: numEggs= 12print('I have %s eggs.' % (numEggs))
7)在字符串首尾忘記加引號(hào)(導(dǎo)致“SyntaxError: EOL while scanning string literal”)
該錯(cuò)誤發(fā)生在如下代碼中:
print(Hello!') 或者: print('Hello!) 或者: myName= 'Al'print('My name is ' + myName+ . How are you?')
8)變量或者函數(shù)名拼寫錯(cuò)誤(導(dǎo)致“NameError: name 'fooba' is not defined”)
該錯(cuò)誤發(fā)生在如下代碼中:
foobar= 'Al'print('My name is ' + fooba) 或者: spam= ruond(4.2) 或者: spam= Round(4.2)
9)方法名拼寫錯(cuò)誤(導(dǎo)致 “AttributeError: 'str' object has no attribute 'lowerr'”)
該錯(cuò)誤發(fā)生在如下代碼中:
新聞熱點(diǎn)
疑難解答
圖片精選