一个小错误可能会导致程序不能运行,这对于初学者程序员来说可能非常令人沮丧。本文将介绍初学者在使用Python可能遇到的常见错误和异常。熟悉这些可以帮助你快速了解问题并解决问题。名称错误当在Python中未定义对象时,你会收到一个 NameError。
语法错误当你在Python中输入不完整时,你会收到一个SyntaxError,比如在定义字符串时,缺少了引号或错误的使用了中文引号。初学者在输入汉字后,经常会出现忘记关闭输入法,错误的输入中文标点符号。类型错误 将函数应用于错误类型的数据时,将出现 TypeError。例如将算术运算应用于字符串。
索引错误当访问超出数据限制的索引时,会收到 IndexError。
键值错误如果尝试访问字典中未包含的键,则会收到 KeyError。
属性错误当使用不适用于正在处理的特定数据的属性或方法时,会发生AttributeError。例如,对数值使用lower()方法。值错误当将函数应用于不适合该操作的数据类型时,会发生值错误。例如,可以将int()应用于整数字符串,例如:int("9999"),但不能将字母转换为整数,int("Hello World!")。缩进错误新手经常犯的另一个错误是缩进错误,这个错误在某种程度上是Python独有的,因为Python使用缩进来定义结构。作为初学者,需要掌握的关键技能是看懂错误信息,错误信息中,通常会告诉你具体的位置,你会很快改正一些常见错误,这对于初学者是很有用的。
>>> str = “Hello World!” SyntaxError: unexpected indent >>> str1="Hello World!" >>> print(str2) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print(str2) NameError: name 'str2' is not defined >>> str1="Hello World! SyntaxError: EOL while scanning string literal >>> str1="Hello World!” SyntaxError: EOL while scanning string literal >>> str1="Hello World!" >>> print(str1+100) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> print(str1+100) TypeError: can only concatenate str (not "int") to str >>> str1="Hello World!" >>> print(str1[20]) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> print(str1[20]) IndexError: string index out of range >>> dict1={"name":"zhangsan","age":20} >>> print(dict1["year"]) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> print(dict1["year"]) KeyError: 'year' >>> n=123 >>> n.lower() Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> n.lower() AttributeError: 'int' object has no attribute 'lower' >>> str1="Hello World!" >>> str2="123" >>> int(str2) 123 >>> int(str1) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> int(str1) ValueError: invalid literal for int() with base 10: 'Hello World!' >>> def f(n): if n>=0: print(n) else: print(-n) SyntaxError: expected an indented block
|