初学Python常见错误

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

1. 忘记写冒号

在 if、elif、else、for、while、def语句后面忘记添加 :

age = 42

if age == 42

    print('Hello!')
File "<ipython-input-19-4303141d6f97>", line 2 if age == 42 ^ SyntaxError: invalid syntax

2. 误用 =

=` 是赋值操作,而判断两个值是否相等是 `==
gender = '男' if gender = '男': print('Man')
File "<ipython-input-20-191d01f95984>", line 2 if gender = '男': ^ SyntaxError: invalid syntax

3. 错误的缩进

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

print('Hello!')

 print('Howdy!')
File "<ipython-input-9-784bdb6e1df5>", line 2 print('Howdy!') ^ IndentationError: unexpected indent
num = 25 if num == 25: print('Hello!')
File "<ipython-input-21-8e4debcdf119>", line 3 print('Hello!') ^ IndentationError: expected an indented block

4. 变量没有定义

if city in ['New York', 'Bei Jing', 'Tokyo']:

    print('This is a mega city')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-22-a81fd2e7a0fd> in <module> ----> 1 if city in ['New York', 'Bei Jing', 'Tokyo']: 2 print('This is a mega city')
NameError: name 'city' is not defined

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

  • 英文冒号
  • 英文括号
  • 英文逗号
  • 英文单双引号
if 5>3:

    print('5比3大')
File "<ipython-input-46-47f8b985b82d>", line 1 if 5>3: ^ SyntaxError: invalid character in identifier
if 5>3: print('5比3大')
File "<ipython-input-47-4b1df4694a8d>", line 2 print('5比3大') ^ SyntaxError: invalid character in identifier
spam = [1, 2,3]
File "<ipython-input-45-47a5de07f212>", line 1 spam = [1, 2,3] ^ SyntaxError: invalid character in identifier
if 5>3: print('5比3大‘)
File "<ipython-input-48-ae599f12badb>", line 2 print('5比3大‘) ^ SyntaxError: EOL while scanning string literal

6. 不同数据类型的拼接

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

字典/集合不支持拼接

'I have ' + 12 + ' eggs.'

#'I have {} eggs.'.format(12)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-20c7c89a2ec6> in <module> ----> 1 'I have ' + 12 + ' eggs.'
TypeError: can only concatenate str (not "int") to str
['a', 'b', 'c']+'def'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-31-0e8919333d6b> in <module> ----> 1 ['a', 'b', 'c']+'def'
TypeError: can only concatenate list (not "str") to list
('a', 'b', 'c')+['a', 'b', 'c']
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-33-90742621216d> in <module> ----> 1 ('a', 'b', 'c')+['a', 'b', 'c']
TypeError: can only concatenate tuple (not "list") to tuple
set(['a', 'b', 'c'])+set(['d', 'e'])
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-ddf5fb1e6c8c> in <module> ----> 1 set(['a', 'b', 'c'])+set(['d', 'e'])
TypeError: unsupported operand type(s) for +: 'set' and 'set'
grades1 = {'Mary':99, 'Henry':77} grades2 = {'David':88, 'Unique':89} grades1+grades2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-36-1b1456844331> in <module> 2 grades2 = {'David':88, 'Unique':89} 3 ----> 4 grades1+grades2
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

7. 索引位置问题

spam = ['cat', 'dog', 'mouse']

print(spam[5])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-38-e0a79346266d> in <module> 1 spam = ['cat', 'dog', 'mouse'] ----> 2 print(spam[5])
IndexError: list index out of range

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

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

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

spam = {'cat': 'Zophie',

        'dog': 'Basil',

        'mouse': 'Whiskers'}

print(spam['zebra'])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-39-92c9b44ff034> in <module> 3 'mouse': 'Whiskers'} 4 ----> 5 print(spam['zebra'])
KeyError: 'zebra'

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

spam = {'cat': 'Zophie',

        'dog': 'Basil',

        'mouse': 'Whiskers'}

print(spam.get('zebra'))
None

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

9. 忘了括号

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

spam = {'cat': 'Zophie',

        'dog': 'Basil',

        'mouse': 'Whiskers'}

print(spam.get('zebra')
File "<ipython-input-43-100a51a7b630>", line 5 print(spam.get('zebra') ^ SyntaxError: unexpected EOF while parsing

10. 漏传参数

def diyadd(x, y, z):

    return x+y+z

diyadd(1, 2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-44-7184f3f906ca> in <module> 2 return x+y+z 3 ----> 4 diyadd(1, 2)
TypeError: diyadd() missing 1 required positional argument: 'z'

11. 缺失依赖库

电脑中没有相关的库

12. 使用了python中的关键词

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

try = 5

print(try)
File "<ipython-input-1-508e87fe2ff3>", line 1 try = 5 ^ SyntaxError: invalid syntax
def = 6 print(6)
File "<ipython-input-2-d04205303265>", line 1 def = 6 ^ SyntaxError: invalid syntax

13. 文件编码问题

import pandas as pd

df = pd.read_csv('data/twitter情感分析数据集.csv')

df.head()

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

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

df.head()

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

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

import chardet

binary_data = open('data/twitter情感分析数据集.csv', 'rb').read()

chardet.detect(binary_data)
{'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''

初学Python常见异常错误,总有一处你会遇到!的更多相关文章

  1. Python常见的错误汇总

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 错误: [错误分析]第二个参数必须为类,否则会报TypeError,所以正确的应 ...

  2. Python常见异常及常用单词翻译

    Python常见异常及常用单词意思 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常:基本上是无法打开文件 ImportE ...

  3. python常见的错误提示处理

    python常见的错误有 NameError变量名错误 IndentationError代码缩进错误 AttributeError对象属性错误 TypeError类型错误 IOError输入输出错误 ...

  4. Python 常见异常类型

    python标准异常 异常名称                                   描述 BaseException                         所有异常的基类Sy ...

  5. Python 常见的错误类型和继承关系

    Python所有的错误都是从BaseException类派生 BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit ...

  6. Python语言常见异常错误类型

    在运行或编写一个程序时常会遇到错误异常,这时python会给你一个错误提示类名,告诉出现了什么样的问题(Python是面向对象语言,所以程序抛出的异常也是类).能很好的理解这些错误提示类名所代表的意思 ...

  7. python常见的错误异常

    1.AssertionError 该异常在assert()语句运行失败时输出 2.AttributeError 该异常在参考或设置属性失败时输出 eg:class Gs: pass g = Gs() ...

  8. python 常见异常

    上面是查看异常的类型 ,知道了异常的类型,才知道怎么捕获这种异常 ================================ AttributeError 不存在属性 IoError  输入或输 ...

  9. python常见异常提示

    PEP8 expected 2 blank lines, found 1 定义方法时,出现期望是2个空白行,但是实际检测到是1个.方法与上面内容间隔期望为两个换行符 PEP8 This diction ...

随机推荐

  1. C#关于MySQL中文乱码问题

      本人在写一个测试demo的时候,遇到一个问题就是添加的中文数据在数据库定义的明明是varchar类型,但是显示出来还是乱码,不过还是自己粗心导致的问题. 以下三种方式可以自查一下: 1. 首先检查 ...

  2. SpringBoot+JWT+Shiro+MybatisPlus实现Restful快速开发后端脚手架

    一.背景 前后端分离已经成为互联网项目开发标准,它会为以后的大型分布式架构打下基础.SpringBoot使编码配置部署都变得简单,越来越多的互联网公司已经选择SpringBoot作为微服务的入门级微框 ...

  3. sprintf函数 (字符格式化函数)

    sprintf函数 字符串格式化命令,主要功能是把格式化的数据写入某个字符串中. sprintf函数原型在<studio.h>中. sprintf( [指向输入格式化后的字符串的缓冲区的指 ...

  4. SpringBoot的启动流程分析(2)

    我们来分析SpringApplication启动流程中的run()方法,代码如下 public ConfigurableApplicationContext run(String... args) { ...

  5. C# Xamarin 数据绑定入门基础

    目录 关于数据绑定 视图-视图绑定 绑定模式 简单的集合绑定 C# Xamarin 数据绑定入门基础 关于数据绑定 Xamarin 单向.双向绑定 Xaml绑定 C#代码绑定 在此之前,几段 伪代码 ...

  6. Spring Boot 2.2.2.RELEASE 版本中文参考文档

    写在前面 在我初次接触MongoDB的时候,是为了做一个监控系统和日志分析系统.当时在用Java操作MongoDB数据里的数据的时候,都是在网上查找Demo示例然后完成的功能,相信大家也同样的体会,网 ...

  7. C#中 EF 性能优化

    https://www.cnblogs.com/chenwolong/p/7531955.html EF使用AsNoTracking(),无跟踪查询技术(查询出来的数据不可以修改,如果你做了修改,你会 ...

  8. Data Management Technology(4) -- 关系数据库理论

    规范化问题的提出 在规范化理论出现以前,层次和网状数据库的设计只是遵循其模型本身固有的原则,而无具体的理论依据可言,因而带有盲目性,可能在以后的运行和使用中发生许多预想不到的问题. 在关系数据库系统中 ...

  9. 解决vue修改路由的查询字符串(query)url不改变,页面不刷新问题

    我个人猜测可能是对路由的数据检测深度不够吧,单纯修改query里面的属性是不能触发数据驱动的,因此要直接给query赋值新的对象才能驱动数据更新,做法如下 第一种 var query=JSON.par ...

  10. 流程控制语句if基本概述

    目录 1. 流程控制语句if基本概述 2. 流程控制语句if文件比较 判断文件是否存在,返回方式 使用变量的方法进行判断 请输入你要备份的数据库名称: wordpress 请输入你要备份的数据库密码: ...