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

开发 后端
本文对初学者总结了13个Python常见异常错误,总有一处你会遇到,快来看看吧!

初学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 "<ipython-input-19-4303141d6f97>" , line       
  5. if age == 42 
  6.               ^  
  7. SyntaxError : invalid syntax 

2. 误用 =

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

 

  1. gender = '男'  
  2. if gender = '男'     
  3. print 'Man' )   
  4. File "<ipython-input-20-191d01f95984>" , line       
  5. if  gender =  '男'  
  6.               ^  
  7. SyntaxError : invalid syntax 

3. 错误的缩进

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

 

  1. print('Hello!' 
  2. print('Howdy!' 
  3.     File "<ipython-input-9-784bdb6e1df5>", line 2  
  4.     print('Howdy!' 
  5.       ^  
  6. IndentationError: unexpected indent  
  7. num = 25  
  8. if num == 25:  
  9.       print('Hello!' 
  10.     File "<ipython-input-21-8e4debcdf119>", 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 lastin  
  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 "<ipython-input-46-47f8b985b82d>", line 1  
  4.    if 5>3:  
  5.           ^  
  6. SyntaxError: invalid character in identifier  
  7. if 5>3:  
  8.      print('5比3大' 
  9.    File "<ipython-input-47-4b1df4694a8d>", line 2  
  10.     print('5比3大' 
  11.                  ^  
  12. SyntaxError: invalid character in identifier  
  13. spam = [1, 2,3]  
  14.     File "<ipython-input-45-47a5de07f212>", line 1  
  15.     spam = [1, 2,3]  
  16.                  ^  
  17. SyntaxError: invalid character in identifier  
  18. if 5>3:  
  19.      print('5比3大‘)  
  20.    File "<ipython-input-48-ae599f12badb>", 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 lastin  
  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 lastin  
  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 lastin  
  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 lastin  
  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 lastin <module>  
  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 lastin  
  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 lastin  
  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 lastin  
  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 " <ipython-input-1-508e87fe2ff3>", line 1  
  3. try = 5 
  4.  
  5. SyntaxError: invalid syntax  
  6. def = 6  
  7. print(6)  
  8. File "<ipython-input-2-d04205303265>", 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'''}  

 

 

责任编辑:庞桂玉 来源: 恋习Python
相关推荐

2014-08-21 14:49:32

MIUI 6

2020-05-26 13:48:05

后端框架异常

2016-10-09 10:29:02

migratelaravelphp

2009-06-06 09:07:05

微软盖茨庄园

2012-10-08 09:59:29

惠普打印

2023-12-28 10:37:16

散弹式更新管理

2019-11-15 14:14:13

Python开发BaseExcepti

2022-10-19 23:18:27

KubernetesPod错误

2017-05-11 08:46:35

全闪存数据中心容量

2019-05-28 08:56:40

PythonCPUThread

2019-08-22 14:02:00

Spring BootRestful APIJava

2023-01-17 09:27:18

Python语言

2015-12-21 11:45:27

C语言常见问题错误

2020-07-27 13:49:47

Python编程语言开发

2023-12-05 14:10:00

接口可读性

2010-11-19 17:11:48

RG-SSO组件五位一体锐捷网络

2023-06-12 08:17:38

Java字符串拼接

2021-01-27 09:41:41

Web安全攻击黑客

2020-07-06 10:29:21

Linux系统数据

2019-10-30 16:03:48

JavaJava虚拟机数据库
点赞
收藏

51CTO技术栈公众号