网站首页 > 基础教程 正文
一个小错误可能会导致程序不能运行,这对于初学者程序员来说可能非常令人沮丧。本文将介绍初学者在使用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
感谢您的阅读,关注我,精彩继续!
猜你喜欢
- 2025-06-23 Python修饰器,终极解释来了!(python修改值)
- 2025-06-23 用Python写爬虫软件的思路(招聘网站为例)
- 2025-06-23 Python微信防撤回,基于itchat模块
- 2025-06-23 菜鸟excel办公自动化:百组数据去重、累加,仅用21行python代码
- 2024-07-28 如何入门Python爬虫?爬虫原理及过程详解
- 2024-07-28 菜鸟用Python操作MongoDB,看这一篇就够了
- 2024-07-28 还在撸Python3.7,Python3.9新鲜出炉,菜鸟哥带你尝鲜解读
- 2024-07-28 字节大佬编写《菜鸟的python笔记》python初学者的福音,建议收藏
- 2024-07-28 10分钟学会用python写游戏!Python其实很简单!
- 2024-07-28 从零开始教你学爬虫!python爬虫的基本流程!
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)