您的位置:首页 > 编程语言 > Python开发

常见Python运行时错误

2016-01-10 21:21 615 查看

“SyntaxError :invalid syntax”

(1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :

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


(2)使用 = 而不是 ==

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


(3)尝试使用Python关键字作为变量名,Python关键不能用作变量名。

(4)错在 ++ 或者 – 自增自减操作符,Python中是没有这样的操作符的。

“IndentationError:unexpected indent”,“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”

错误的使用缩进量,记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。

“TypeError: ‘list’ object cannot be interpreted as an integer”

在 for 循环语句中忘记调用 len() ,通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。

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


“TypeError: ‘str’ object does not support item assignment”

尝试修改string的值,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.')

//正确做法1:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

//正确做法2:
numEggs = 12
print('I have %s eggs.' % (numEggs))


“SyntaxError: EOL while scanning string literal”

在字符串首尾忘记加引号。

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


“NameError: name ‘fooba’ is not defined”

变量或者函数名拼写错误。

foobar = 'Tom'
print('My name is ' + fooba)


“AttributeError: ‘str’ object has no attribute ‘lowerr’”

方法名拼写错误。

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()


“IndexError: list index out of range”

引用超过list最大索引。

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


“KeyError:‘spam’”

使用不存在的字典键值。

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


“TypeError: myMethod() takes no arguments (1 given)”

忘记为方法的第一个参数添加self参数。

class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 错误提示