初学python最容易犯的13个错误,你犯过几个呢?
bigegpt 2024-10-08 00:46 9 浏览
Python 以其简单易懂的语法格式与其它语言形成鲜明对比,初学者遇到最多的问题就是不按照 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、用关键字做变量名
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的学习资料,如果你想提升自己,对编程感兴趣,关注我并在后台私信小编:“08”即可免费领取资料!
相关推荐
- pyproject.toml到底是什么东西?(py trim)
-
最近,在Twitter上有一个Python项目的维护者,他的项目因为构建失败而出现了一些bug(这个特别的项目不提供wheel,只提供sdist)。最终,发现这个bug是由于这个项目使用了一个pypr...
- BDP服务平台SDK for Python3发布(bdp数据平台)
-
下载地址https://github.com/imysm/opends-sdk-python3.git说明最近在开发和bdp平台有关的项目,用到了bdp的python的sdk,但是官方是基于p...
- Python-for-Android (p4a):(python-for-android p4a windows)
-
一、Python-for-Android(p4a)简介Python-for-Android(p4a),一个强大的开发工具,能够将你的Python应用程序打包成可在Android设备上运行...
- Qt for Python—Qt Designer 概览
-
前言本系列第三篇文章(QtforPython学习笔记—应用程序初探)、第四篇文章(QtforPython学习笔记—应用程序再探)中均是使用纯代码方式来开发PySide6GUI应用程序...
- Python:判断质数(jmu-python-判断质数)
-
#Python:判断质数defisPrime(n):foriinrange(2,n):ifn%i==0:return0re...
- 为什么那么多人讨厌Python(为什么python这么难)
-
Python那么棒,为什么那么多人讨厌它呢?我整理了一下,主要有这些原因:用缩进替代大括号许多人抱怨Python完全依赖于缩进来创建代码块,代码多一点就很难看到函数在哪里结束,那么你就需要把一个函数拆...
- 一文了解 Python 中带有 else 的循环语句 for-else/while-else
-
在本文中,我们将向您介绍如何在python中使用带有else的for/while循环语句。可能许多人对循环和else一起使用感到困惑,因为在if-else选择结构中else正常...
- python的numpy向量化语句为什么会比for快?
-
我们先来看看,python之类语言的for循环,和其它语言相比,额外付出了什么。我们知道,python是解释执行的。举例来说,执行x=1234+5678,对编译型语言,是从内存读入两个shor...
- 开眼界!Python遍历文件可以这样做
-
来源:【公众号】Python技术Python对于文件夹或者文件的遍历一般有两种操作方法,一种是至二级利用其封装好的walk方法操作:import osfor root,d...
- 告别简单format()!Python Formatter类让你的代码更专业
-
Python中Formatter类是string模块中的一个重要类,它实现了Python字符串格式化的底层机制,允许开发者创建自定义的格式化行为。通过深入理解Formatter类的工作原理和使用方法,...
- python学习——038如何将for循环改写成列表推导式
-
在Python里,列表推导式是一种能够简洁生成列表的表达式,可用于替换普通的for循环。下面是列表推导式的基本语法和常见应用场景。基本语法result=[]foriteminite...
- 详谈for循环和while循环的区别(for循环语句与while循环语句有什么区别)
-
初九,潜龙勿用在刚开始使用python循环语句时,经常会遇到for循环和while循环的混用,不清楚该如何选择;今天就对这2个循环语句做深入的分析,让大家更好地了解这2个循环语句以方便后续学习的加深。...
- Python编程基础:循环结构for和while
-
Python中的循环结构包括两个,一是遍历循环(for循环),一是条件循环(while循环)。遍历循环遍历循环(for循环)会挨个访问序列或可迭代对象的元素,并执行里面的代码块。foriinra...
- 学习编程第154天 python编程 for循环输出菱形图
-
今天学习的是刘金玉老师零基础Python教程第38期,主要内容是python编程for循环输出菱形※。(一)利用for循环输出菱形形状的*号图形1.思路:将菱形分解为上下两个部分三角形图案,分别利用...
- python 10个堪称完美的for循环实践
-
在Python中,for循环的高效使用能显著提升代码性能和可读性。以下是10个堪称完美的for循环实践,涵盖数据处理、算法优化和Pythonic编程风格:1.遍历列表同时获取索引(enumerate...
- 一周热门
- 最近发表
-
- pyproject.toml到底是什么东西?(py trim)
- BDP服务平台SDK for Python3发布(bdp数据平台)
- Python-for-Android (p4a):(python-for-android p4a windows)
- Qt for Python—Qt Designer 概览
- Python:判断质数(jmu-python-判断质数)
- 为什么那么多人讨厌Python(为什么python这么难)
- 一文了解 Python 中带有 else 的循环语句 for-else/while-else
- python的numpy向量化语句为什么会比for快?
- 开眼界!Python遍历文件可以这样做
- 告别简单format()!Python Formatter类让你的代码更专业
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- linux安装minio (74)
- ubuntuunzip (67)
- vscode使用技巧 (83)
- secure-file-priv (67)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)