首页 后端开发 Python教程 python中一些常见的错误

python中一些常见的错误

Jun 16, 2020 pm 03:53 PM
python

python中一些常见的错误

python中常见的错误:

0、忘记写冒号

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

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、用关键字做变量名

class = 'algebra'
登录后复制

导致:SyntaxError: invalid syntax

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

>>> import keyword
>>> print(keyword.kwlist)
['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

method1 是 Foo 类的一个成员方法,该方法不接受任何参数,调用 a.method1() 相当于调用 Foo.method1(a),但 method1 不接受任何参数,所以报错了。正确的调用方式应该是 Foo.method1()。

更多相关知识请关注python视频教程栏目

以上是python中一些常见的错误的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Linux系统自带Python解释器能删除吗? Linux系统自带Python解释器能删除吗? Apr 02, 2025 am 07:00 AM

关于Linux系统自带Python解释器的删除问题许多Linux发行版在安装时会预装Python解释器,它并非通过软件包管理器�...

如何解决Python中自定义装饰器的Pylance类型检测问题? 如何解决Python中自定义装饰器的Pylance类型检测问题? Apr 02, 2025 am 06:42 AM

使用自定义装饰器时的Pylance类型检测问题解决方法在Python编程中,装饰器是一种强大的工具,可以用于添加行�...

在Linux终端中使用python --version命令时如何解决权限问题? 在Linux终端中使用python --version命令时如何解决权限问题? Apr 02, 2025 am 06:36 AM

Linux终端中使用python...

Python 3.6加载pickle文件报错ModuleNotFoundError: No module named '__builtin__'怎么办? Python 3.6加载pickle文件报错ModuleNotFoundError: No module named '__builtin__'怎么办? Apr 02, 2025 am 06:27 AM

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

FastAPI 和 aiohttp 是否共享同一个全局事件循环? FastAPI 和 aiohttp 是否共享同一个全局事件循环? Apr 02, 2025 am 06:12 AM

Python异步库之间的兼容性问题在Python中,异步编程已经成为处理高并发和I/O...

Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办? Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办? Apr 02, 2025 am 07:12 AM

Python3.6环境下加载Pickle文件报错:ModuleNotFoundError:Nomodulenamed...

如何在Python中通过信号杀死父进程后确保子进程也终止? 如何在Python中通过信号杀死父进程后确保子进程也终止? Apr 02, 2025 am 06:39 AM

使用信号杀死父进程时,子进程继续运行的问题及解决方案在Python编程中,通过信号杀死父进程后,子进程仍然...

See all articles