Python初学者常见错误详解

Python初学者常见错误详解

0、忘记写冒号

在 if、elif、else、for、while、class、def 语句后面忘记添加 “:”

 

if spam == 42

print('Hello!')

导致:SyntaxError: invalid syntax

1、误用 “=” 做等值比较

“=” 是赋值操作,而判断两个值是否相等是 “==”

 

if spam = 42:

print('Hello!')

导致:SyntaxError: invalid syntax

2、使用错误的缩进

Python用缩进区分代码块,常见的错误用法:

 

print('Hello!')

print('Howdy!')

导致:IndentationError: unexpected indent。同一个代码块中的每行代码都必须保持一致的缩进量

 

if spam == 42:

print('Hello!')

print('Howdy!')

导致:IndentationError: unindent does not match any outer indentation level。代码块结束之后缩进恢复到原来的位置

 

if spam == 42:

print('Hello!')

导致:IndentationError: expected an indented block,“:” 后面要使用缩进

3、变量没有定义

 

if spam == 42:

print('Hello!')

导致:NameError: name 'spam' is not defined

4、获取列表元素索引位置忘记调用 len 方法

通过索引位置获取元素的时候,忘记使用 len 函数获取列表的长度。

 

spam = ['cat', 'dog', 'mouse']

for i in range(spam):

print(spam[i])

导致:TypeError: range() integer end argument expected, got list. 正确的做法是:

 

spam = ['cat', 'dog', 'mouse']

for i in range(len(spam)):

print(spam[i])

当然,更 Pythonic 的写法是用 enumerate

 

spam = ['cat', 'dog', 'mouse']

for i, item in enumerate(spam):

print(i, item)

5、修改字符串

字符串一个序列对象,支持用索引获取元素,但它和列表对象不同,字符串是不可变对象,不支持修改。

 

spam = 'I have a pet cat.'

spam[13] = 'r'

print(spam)

导致:TypeError: 'str' object does not support item assignment 正确地做法应该是:

 

spam = 'I have a pet cat.'

spam = spam[:13] + 'r' + spam[14:]

print(spam)

6、字符串与非字符串连接(类型错误,常见的是字符串和数字直接拼接在一起)

 

num_eggs = 12

print('I have ' + num_eggs + ' eggs.')

导致:TypeError: cannot concatenate 'str' and 'int' objects

字符串与非字符串连接时,必须把非字符串对象强制转换为字符串类型

 

num_eggs = 12

print('I have ' + str(num_eggs) + ' eggs.')

或者使用字符串的格式化形式

 

num_eggs = 12

print('I have %s eggs.' % (num_eggs))

7、使用错误的索引位置(下标越界)

 

spam = ['cat', 'dog', 'mouse']

print(spam[3])

导致:IndexError: list index out of range

列表对象的索引是从0开始的,第3个元素应该是使用 spam[2] 访问

8、字典中使用不存在的键

 

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}

print('The name of my pet zebra is ' + spam['zebra'])

在字典对象中访问 key 可以使用 [],但是如果该 key 不存在,就会导致:KeyError: 'zebra'

正确的方式应该使用 get 方法

 

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}

print('The name of my pet zebra is ' + spam.get('zebra'))

key 不存在时,get 默认返回 None

9、用python关键字做变量名

 

class = 'algebra'

导致:SyntaxError: invalid syntax

在 Python 中不允许使用关键字作为变量名。Python3 一共有33个关键字。

 

>>> import keyword

>>> print(keyword.kwlist)

Python关键字:['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

10、函数中局部变量赋值前被使用

 

 

someVar = 42

def myFunction():

print(someVar)

someVar = 100

myFunction()

导致:UnboundLocalError: local variable 'someVar' referenced before assignment

当函数中有一个与全局作用域中同名的变量时,它会按照 LEGB 的顺序查找该变量,如果在函数内部的局部作用域中也定义了一个同名的变量,那么就不再到外部作用域查找了。因此,在 myFunction 函数中 someVar 被定义了,所以 print(someVar) 就不再外面查找了,但是 print 的时候该变量还没赋值,所以出现了 UnboundLocalError

11、使用自增 “++” 自减 “--”

 

spam = 0

spam++

Python 中没有自增自减操作符,如果你是从C、Java转过来的话,你可要注意了。你可以使用 “+=” 来替代 “++”

 

spam = 0

spam += 1

12、错误地调用类中的方法

 

 

 

 

class Foo:

def method1():

print('m1')

def method2(self):

print("m2")

a = Foo()

a.method1()

导致:TypeError: method1() takes 0 positional arguments but 1 was given

13、尝试修改string的值

string是一种不可变的数据类型,该错误发生在如下代码中:

 

spam = 'I have apet cat.'

spam[13] = 'r'

print(spam)

而你实际想要这样做:

 

spam = 'I have apet cat.'

spam = spam[:13] +'r' + spam[14:]

print(spam)

导致:TypeError:'str'object does not support item assignment

14、在字符串首尾忘记加引号

该错误发生在如下代码中:

 

print(Hello!')

或者:

print('Hello!)

或者:

myName = 'Al'

print('My name is '+ myName + . How are you?')

导致:SyntaxError:EOL while scanning string literal

15、变量或者函数名拼写错误

该错误发生在如下代码中:

 

foobar = 'Al'

print('My name is '+ fooba)

或者:

spam = ruond(4.2)

或者:

spam = Round(4.2)

导致:NameError:name 'fooba' is not defined

python中常见的报错信息

 搜集了一些python最重要的内建异常类名:

1.  AttributeError:对象属性错误,特性引用和赋值失败时会引发属性错误(eg.元祖对象没有“append”的属性,元祖是不可变对象)—说明该对象中没有这种属性

  1. NameError:试图访问的变量名不存在,变量名错误(需要先定义变量并赋值)

3.  SyntaxError:语法错误,代码形式错误

4.  Exception:所有异常的基类,因为所有python异常类都是基类Exception的其中一员,异常都是从基类Exception继承的,并且都在exceptions模块中定义。

  1. IOError:一般常见于打开不存在文件时会引发IOError错误,也可以解理为输出输入错误

6.  KeyError:使用了映射中不存在的key和value时引发的错误,字典键值错误(值错误,没有找到输入的字符串,方法参数有问题)

7.  IndexError:索引错误,使用的索引不存在,常索引超出序列范围,什么是索引

8. TypeError:类型错误,内建操作或是函数应用在了错误类型的对象

9.  ZeroDivisonError:除数为0,在用除法操作时,第二个参数为0

10.  ValueError:值错误,传给对象的参数类型不正确,像是给int()函数传入了字符串数据类型的参数。

11. IndentationError代码缩进错误

12. TabError: Tab 和空格混用

 

try……except……捕获异常

#捕获特殊异常

while True:

    try:

        age = int(input('你今年几岁了?'))

        break

    except ValueError:

        print('你输入的不是数字!')

猜你喜欢

转载自www.cnblogs.com/lcljyb/p/12010064.html