python常见运行错误
2018-03-31 12:58
357 查看
1. SyntaxError :invalid syntax
1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 “:”2)使用 = 而不是 ==
3)错误的使用缩进量
4) 尝试使用Python关键字作为变量名
5)错在 ++ 或者 – 自增自减操作符
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
2.1 TypeError: ‘list’ object cannot be interpreted as an integer
在 for 循环语句中忘记调用 len()spam = ['cat', 'dog', 'mouse'] for i in range(spam): print(spam[i])
2.2 TypeError: myMethod() takes no arguments (1 given)
忘记为方法的第一个参数添加self参数class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()
2.3 TypeError: ‘range’ object does not support item assignment
有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值#错误方法 spam = range(10) #正确方法 spam = list(range(10)) spam[4] = -1
3. TypeError: ‘str’ object does not support item assignment
尝试修改string的值,string是一种不可变的数据类型spam = 'I have a pet cat.' spam[13] = 'r' print(spam)
4.TypeError: Can’t convert ‘int’ object to str implicitly
numEggs = 12 print('I have ' + numEggs + ' eggs.') # 应该先转换12:str(numEggs)
5. NameError: name ‘fooba’ is not defined
变量或者函数名拼写错误6. AttributeError: ‘str’ object has no attribute ‘lowerr
方法名拼写错误7. IndexError: list index out of range
引用超过list最大索引8. KeyError
使用不存在的字典键值8. UnboundLocalError: local variable ‘foobar’ referenced before assignment
在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。这意味着你不能在定义它之前把它当全局变量在函数中使用。
该错误发生在如下代码中:
someVar = 42 def myFunction(): print(someVar) someVar = 100 myFunction()
原文链接
相关文章推荐
- Python运行的17个时新手常见错误小结
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- Python运行的17个时新手常见错误小结
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- 17个新手常见的Python运行时错误
- 常见Python运行时错误
- Python基础学习-17个新手常见Python运行时错误
- 【Python】17个新手常见Python运行时错误
- [转]17个新手常见的Python运行时错误
- 17个新手常见Python运行时错误
- Python运行的17个时新手常见错误小结
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- 17个新手常见Python运行时错误
- 新手常见的17个Python运行错误