搜索
首页后端开发Python教程初学者学习Python时常见的错误总结

最近学习Python,现在把一些常见的错误总结如下:

1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :(导致 “SyntaxError :invalid syntax”) 该错误将发生在类似如下代码中:

if spam == 42 print('Hello!')

2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”) = 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:

if spam = 42: print('Hello!')

3)错误的使用缩进量。(导致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”) 记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:

print('Hello!') 
   print('Howdy!')

或者:

if spam == 42: 
print('Hello!') 
print('Howdy!')

或者:

 if spam == 42: 
print('Hello!')

4)在 for 循环语句中忘记调用 len() (导致“TypeError: 'list' object cannot be interpreted as an integer”) 通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。 该错误发生在如下代码中:

spam = ['cat', 'dog', 'mouse'] 
for i in range(spam): 
     print(spam[i])

5)尝试修改string的值(导致“TypeError: 'str' object does not support item assignment”) 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)

6)尝试连接非字符串值与字符串(导致 “TypeError: Can't convert 'int' object to str implicitly”) 该错误发生在如下代码中:

numEggs = 12 print('I have ' + numEggs + ' eggs.')

而你实际想要这样做:

numEggs = 12 print('I have ' + str(numEggs) + ' eggs.')

或者:

 numEggs = 12 print('I have %s eggs.' % (numEggs))

7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”) 该错误发生在如下代码中:

print(Hello!') 或者: print('Hello!)

或者:

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

8)变量或者函数名拼写错误(导致“NameError: name 'fooba' is not defined”) 该错误发生在如下代码中:

foobar = 'Al' print('My name is ' + fooba)
 或者:
spam = ruond(4.2) 
或者: 
spam = Round(4.2)

9)方法名拼写错误(导致 “AttributeError: 'str' object has no attribute 'lowerr'”) 该错误发生在如下代码中:

spam = 'THIS IS IN LOWERCASE.' 
spam = spam.lowerr()

10)引用超过list最大索引(导致“IndexError: list index out of range”) 该错误发生在如下代码中:

spam = ['cat', 'dog', 'mouse'] 
print(spam[6])

11)使用不存在的字典键值(导致“KeyError:‘spam'”) 该错误发生在如下代码中:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12)尝试使用Python关键字作为变量名(导致“SyntaxError:invalid syntax”) Python关键不能用作变量名,该错误发生在如下代码中:

class = 'algebra'

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

13)在一个定义新变量中使用增值操作符(导致“NameError: name 'foobar' is not defined”) 不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。 该错误发生在如下代码中:

spam = 0 
spam += 42 
eggs += 42

14)在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“UnboundLocalError: local variable 'foobar' referenced before assignment”) 在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。 这意味着你不能在定义它之前把它当全局变量在函数中使用。 该错误发生在如下代码中:

someVar = 42 
def myFunction(): 
   print(someVar) 
   someVar = 100 
   myFunction()

15)尝试使用 range()创建整数列表(导致“TypeError: 'range' object does not support item assignment”) 有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。 该错误发生在如下代码中:

spam = range(10) 
spam[4] = -1

也许这才是你想做:

spam = list(range(10)) 
spam[4] = -1

(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)

16)错在 ++ 或者 -- 自增自减操作符。(导致“SyntaxError: invalid syntax”) 如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。 该错误发生在如下代码中:

spam = 1
spam++

也许这才是你想做的:

spam = 1 
spam += 1

17)忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”) 该错误发生在如下代码中:

class Foo(): def myMethod(): 
       print('Hello!') a = Foo() a.myMethod()


 

以上是初学者学习Python时常见的错误总结的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

阵列的同质性质如何影响性能?阵列的同质性质如何影响性能?Apr 25, 2025 am 12:13 AM

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

编写可执行python脚本的最佳实践是什么?编写可执行python脚本的最佳实践是什么?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy数组与使用数组模块创建的数组有何不同?Numpy数组与使用数组模块创建的数组有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

Numpy数组的使用与使用Python中的数组模块阵列相比如何?Numpy数组的使用与使用Python中的数组模块阵列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模块与Python中的数组有何关系?CTYPES模块与Python中的数组有何关系?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

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

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具