當初學 Python 時,想要弄懂 Python 的錯誤信息的含義可能有點復雜。這里列出了常見的的一些讓你程序 crash 的運行時錯誤
該錯誤將發生在類似如下代碼中:
if spam == 42
print('Hello!')
if spam = 42:
print('Hello!')
(導致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)
python的typeerror,記住縮進增加只用在以:結束的語句之后,而之后必須恢復到之前的縮進格式。該錯誤發生在如下代碼中:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
通常你想要通過索引來迭代一個list或者string的元素,這需要調用 range() 函數。要記得返回len 值而不是返回這個列表。
該錯誤發生在如下代碼中:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
python報錯unicodedecodeerror、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)
(導致 “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))
pythontype,該錯誤發生在如下代碼中:
print(Hello!')
或者:
print('Hello!)
或者:
myName = 'Al'
print('My name is ' + myName + . How are you?')
foobar = 'Al'
print('My name is ' + fooba)
或者:
spam = ruond(4.2)
或者:
spam = Round(4.2)
該錯誤發生在如下代碼中:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
該錯誤發生在如下代碼中:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
該錯誤發生在如下代碼中:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
Python關鍵不能用作變量名,該錯誤發生在如下代碼中:
class = 'algebra'
python異常拋出。Python3的關鍵字有:and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
不要在聲明變量時使用0或者空字符串作為初始值,這樣使用自增操作符的一句spam += 1等于spam = spam + 1,這意味著spam需要指定一個有效的初始值。
該錯誤發生在如下代碼中:
spam = 0
spam += 42
eggs += 42
(此時有與局部變量同名的全局變量存在)(導致“UnboundLocalError: local variable ‘foobar’ referenced before assignment”)
在函數中使用局部變來那個而同時又存在同名全局變量時是很復雜的,使用規則是:如果在函數中定義了任何東西,如果它只是在函數中使用那它就是局部的,反之就是全局變量。
typeerror?這意味著你不能在定義它之前把它當全局變量在函數中使用。
該錯誤發生在如下代碼中:
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()
有時你想要得到一個有序的整數列表,所以 range() 看上去是生成此列表的不錯方式。然而,你需要記住 range() 返回的是 “range object”,而不是實際的 list 值。
該錯誤發生在如下代碼中:
spam = range(10)
spam[4] = -1
也許這才是你想做:
spam = list(range(10))
spam[4] = -1
list python,(注意:在 Python 2 中 spam = range(10) 是能行的,因為在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就會產生以上錯誤)
16)不錯在 ++ 或者 – 自增自減操作符。(導致“SyntaxError: invalid syntax”)
如果你習慣于例如 C++ , Java , PHP 等其他的語言,也許你會想要嘗試使用 ++ 或者 – 自增自減一個變量。在Python中是沒有這樣的操作符的。
該錯誤發生在如下代碼中:
spam = 1
spam++
也許這才是你想做的:
spam = 1
spam += 1
qpython?該錯誤發生在如下代碼中:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态