初学Python常见异常错误,总有一处你会遇到!
创始人
2025-03-18 21:41:11
0次

初学Python常见异常错误,总有一处你会遇到!

初学Python常见错误

  1. 忘记写冒号
  2. 误用=
  3. 错误 缩紧
  4. 变量没有定义
  5. 中英文输入法导致的错误
  6. 不同数据类型的拼接
  7. 索引位置问题
  8. 使用字典中不存在的键
  9. 忘了括号
  10. 漏传参数
  11. 缺失依赖库
  12. 使用了python中对关键词
  13. 编码问题

1. 忘记写冒号

在 if、elif、else、for、while、def语句后面忘记添加 :age = 42if age == 42 print('Hello!')

  1. age =  42  
  2. if age ==  42      
  3. print ( 'Hello!' )     
  4. File "" , line  2      
  5. if age == 42 
  6.               ^  
  7. SyntaxError : invalid syntax 

2. 误用 =

= 是赋值操作,而判断两个值是否相等是 ==

 

  1. gender = '男'  
  2. if gender = '男' :     
  3. print ( 'Man' )   
  4. File "" , line  2      
  5. if  gender =  '男' :  
  6.               ^  
  7. SyntaxError : invalid syntax 

3. 错误的缩进

Python用缩进区分代码块,常见的错误用法:

 

  1. print('Hello!')  
  2. print('Howdy!')  
  3.     File "", line 2  
  4.     print('Howdy!')  
  5.       ^  
  6. IndentationError: unexpected indent  
  7. num = 25  
  8. if num == 25:  
  9.       print('Hello!')  
  10.     File "", line 3  
  11.     print('Hello!')  
  12.        ^  
  13. IndentationError: expected an indented block 

4. 变量没有定义

 

  1. if city in ['New York', 'Bei Jing', 'Tokyo']: print('This is a mega city')  
  2. ---------------------------------------------------------------------------  
  3. NameError Traceback (most recent call last) in  
  4. ----> 1 if city in ['New York', 'Bei Jing', 'Tokyo']:  
  5.         2 print('This is a mega city')  
  6. NameError: name 'city' is not defined 

 

5. 中英文输入法导致的错误

  • 英文冒号
  • 英文括号
  • 英文逗号
  • 英文单双引号

 

  1. if 5>3:  
  2.     print('5比3大')  
  3.    File "", line 1  
  4.    if 5>3:  
  5.           ^  
  6. SyntaxError: invalid character in identifier  
  7. if 5>3:  
  8.      print('5比3大')  
  9.    File "", line 2  
  10.     print('5比3大')  
  11.                  ^  
  12. SyntaxError: invalid character in identifier  
  13. spam = [1, 2,3]  
  14.     File "", line 1  
  15.     spam = [1, 2,3]  
  16.                  ^  
  17. SyntaxError: invalid character in identifier  
  18. if 5>3:  
  19.      print('5比3大‘)  
  20.    File "", line 2  
  21.     print('5比3大‘)  
  22.                ^  
  23. SyntaxError: EOL while scanning string literal 

6. 不同数据类型的拼接

字符串/列表/元组 支持拼接

字典/集合不支持拼接

 

  1. 'I have ' + 12 + ' eggs.  
  2. '#'I have {} eggs.'.format(12)  
  3. ---------------------------------------------------------------------------  
  4. TypeError                  Traceback (most recent call last) in  
  5. ----> 1 'I have ' + 12 + ' eggs.'  
  6. TypeError: can only concatenate str (not "int") to str  
  7. ['a', 'b', 'c']+'def'  
  8. ---------------------------------------------------------------------------  
  9. TypeError                     Traceback (most recent call last) in  
  10. ----> 1 ['a', 'b', 'c']+'def'  
  11. TypeError: can only concatenate list (not "str") to list  
  12. ('a', 'b', 'c')+['a', 'b', 'c']  
  13. ---------------------------------------------------------------------------  
  14. TypeError                     Traceback (most recent call last) in  
  15. ----> 1 ('a', 'b', 'c')+['a', 'b', 'c']  
  16. TypeError: can only concatenate tuple (not "list") to tuple  
  17. set(['a', 'b', 'c'])+set(['d', 'e'])  
  18. ---------------------------------------------------------------------------  
  19. TypeError                   Traceback (most recent call last) in  
  20. ----> 1 set(['a', 'b', 'c'])+set(['d', 'e'])  
  21. TypeError: unsupported operand type(s) for +: 'set' and 'set'  
  22. grades1 = {'Mary':99, 'Henry':77}  
  23. grades2 = {'David':88, 'Unique':89}  
  24. grades1+grades2  
  25. ---------------------------------------------------------------------------  
  26. TypeError             Traceback (most recent call last) in   
  27.         2 grades2 = {'David':88, 'Unique':89}  
  28.         3  
  29. ----> 4 grades1+grades2  
  30. TypeError: unsupported operand type(s) for +: 'dict' and 'dict' 

 

7. 索引位置问题

 

  1. spam = ['cat', 'dog', 'mouse']
  2. print(spam[5])  
  3. ---------------------------------------------------------------------------  
  4. IndexError                    Traceback (most recent call last) in  
  5. 1 spam = ['cat', 'dog', 'mouse']
  6. ----> 2 print(spam[5])  
  7. IndexError: list index out of range 

 

8. 使用字典中不存在的键

在字典对象中访问 key 可以使用 [],

但是如果该 key 不存在,就会导致:KeyError: 'zebra'

 

  1. spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}  
  2. print(spam['zebra'])  
  3. ---------------------------------------------------------------------------  
  4. KeyError                 Traceback (most recent call last) in  
  5.         3 'mouse': 'Whiskers'}  
  6.         4  
  7. ----> 5 print(spam['zebra'])  
  8. KeyError: 'zebra' 

 

为了避免这种情况,可以使用 get 方法

 

  1. spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}  
  2. print(spam.get('zebra'))  
  3. None 

 

key 不存在时,get 默认返回 None

9. 忘了括号

当函数中传入的是函数或者方法时,容易漏写括号

 

  1. spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}  
  2. print(spam.get('zebra')  
  3. File "", line 5  
  4. print(spam.get('zebra')  
  5.                     ^  
  6. SyntaxError: unexpected EOF while parsing 

10. 漏传参数

 

  1. def diyadd(x, y, z): return x+y+zdiyadd(1, 2)  
  2. ---------------------------------------------------------------------------  
  3. TypeError                Traceback (most recent call last) in  
  4.                  2 return x+y+z  
  5.                  3  
  6.           ----> 4 diyadd(1, 2)  
  7. TypeError: diyadd() missing 1 required positional argument: 'z' 

 

11. 缺失依赖库

电脑中没有相关的库

12. 使用了python中的关键词

如try、except、def、class、object、None、True、False等

 

  1. try = 5print(try)  
  2. File " ", line 1  
  3. try = 5 
  4. ^  
  5. SyntaxError: invalid syntax  
  6. def = 6  
  7. print(6)  
  8. File "", line 1  
  9. def = 6  
  10. ^  
  11. SyntaxError: invalid syntax 

13. 文件编码问题

 

  1. import pandas as pd  
  2. df = pd.read_csv('data/twitter情感分析数据集.csv')  
  3. df.head() 

 

尝试encoding编码参数传入utf-8、gbk

 

  1. df = pd.read_csv('data/twitter情感分析数据集.csv', encoding='utf-8')  
  2. df.head() 

 

都报错说明编码不是utf-8和gbk,而是不常见都编码,这里我们需要传入正确都encoding,才能让程序运行。

python有个chardet库,专门用来侦测编码。

 

  1. import chardet  
  2. binary_data = open('data/twitter情感分析数据集.csv', 'rb').read()  
  3. chardet.detect(binary_data)  
  4. {'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''}  

 

 

相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
粉嫩如何诠释霸道 东芝M805... “霸道粉”是个什么玩意东芝M805拿过来的时候,笔者扑哧笑了,不是笑这款笔记本,而是笑这款产品的颜色...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
只需三步,让你掌握阿尔法路由器... 请参照以下阿尔法路由器设置方法,通过浏览器进入及设置宽带路由器。经过这三个步骤的设置,基本上能够熟悉...
如何更省钱? 近期特价热门硒鼓... 如今激光打印设备已经成为商务或企业的绝对主力办公设备,但采购者往往忽视了激光打印设备所用的耗材,相对...
全面诠释网络负载均衡 负载均衡的出现大大缓解了服务器的压力,更是有效的利用了资源,提高了效率。那么我们现在来说一下网络负载...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...