常见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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法