1)忘記在 if , elif , else , for , while , class ,def 聲明末尾添加 :(導致 “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!') 或者: if spam== 42:print('Hello!')
4)在 for 循環語句中忘記調用 len() (導致“TypeError: 'list' object cannot be interpreted as an integer”)
通常你想要通過索引來迭代一個list或者string的元素,這需要調用 range() 函數。要記得返回len 值而不是返回這個列表。
該錯誤發生在如下代碼中:
spam= ['cat','dog','mouse']for iin 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= 12print('I have ' + numEggs+ ' eggs.')
而你實際想要這樣做:
numEggs= 12print('I have ' + str(numEggs)+ ' eggs.') 或者: numEggs= 12print('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'”)
該錯誤發生在如下代碼中:
新聞熱點
疑難解答