14种常见错误
Python语法入门-课件下载
链接: https://pan.baidu.com/s/1h1RuWimLicVanK8xCka_xA 提取码: x264
学习编程就是在遇到错误、认识错误、解决错误的过程。遇到错误,大家要发挥主观能动性,用自己的英文阅读能力去先读一下英文报错提示,一般情况下错误提示会告诉你是什么类型的错误,错误出在哪一行。
再结合百度谷歌,80%以上的问题都能解决。现在我们了解一下常见的问题都有哪些,如何克服这些问题。
1. 忘记写冒号
在 if、elif、else、for、while、def语句后面忘记添加 :
age = 42
if age == 42
print('Hello!')
File "<ipython-input-10-1f5acea116cf>", line 3
if age == 42
^
SyntaxError: invalid syntax
age = 42
if age == 42:
print('Hello!')
Hello!
2. 误用 =
=
是赋值操作,而判断两个值是否相等是 ==
gender = '男'
if gender = '男':
print('Man')
File "<ipython-input-12-c3ceea5a9004>", line 3
if gender = '男':
^
SyntaxError: invalid syntax
gender = '男'
if gender == '男':
print('Man')
Man
3. 错误的缩进
Python用缩进区分代码块,常见的错误用法:
print('Hello!')
print('Howdy!')
File "<ipython-input-14-784bdb6e1df5>", line 2
print('Howdy!')
^
IndentationError: unexpected indent
print('Hello!')
print('Howdy!')
Hello!
Howdy!
num = 25
if num == 25:
print('Hello!')
File "<ipython-input-16-8e4debcdf119>", line 3
print('Hello!')
^
IndentationError: expected an indented block
num = 25
if num == 25:
print('Hello!')
Hello!
4. 变量没有定义
if c in ['New York', 'Bei Jing', 'Tokyo']:
print('This is a mega city')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-21-d91d0b36da73> in <module>
----> 1 if c in ['New York', 'Bei Jing', 'Tokyo']:
2 print('This is a mega c')
NameError: name 'c' is not defined
city ='New York'
if city in ['New York', 'Bei Jing', 'Tokyo']:
print('This is a mega city')
This is a mega city
5. 中英文输入法导致的错误
- 英文冒号
- 英文括号
- 英文逗号
- 英文单双引号
if 5>3:
print('5比3大')
File "<ipython-input-23-47f8b985b82d>", line 1
if 5>3:
^
SyntaxError: invalid character in identifier
if 5>3:
print('5比3大')
5比3大
spam = [1, 2, 3]
File "<ipython-input-26-a003060d051a>", line 1
spam = [1, 2, 3]
^
SyntaxError: invalid character in identifier
spam = [1, 2, 3]
spam
[1, 2, 3]
if 5>3:
print('5比3大’)
File "<ipython-input-30-ac2e4eb87092>", line 2
print('5比3大’)
^
SyntaxError: EOL while scanning string literal
if 5>3:
print('5比3大')
5比3大
6. 不同数据类型的拼接
同种数据类型 字符串/列表/元组 支持拼接
字典/集合不支持拼接
'I have ' + 12 + ' eggs.'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-20c7c89a2ec6> in <module>
----> 1 'I have ' + 12 + ' eggs.'
TypeError: can only concatenate str (not "int") to str
'I have {} eggs.'.format(12)
'I have 12 eggs.'
['a', 'b', 'c']+'def'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-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-36-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-37-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-38-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-41-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-42-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') #end of funtion
File "<ipython-input-44-d105cc86097c>", line 5
print(spam.get('zebra') #end of funtion
^
SyntaxError: unexpected EOF while parsing
spam = {'cat': 'Zophie',
'dog': 'Basil',
'mouse': 'Whiskers'}
print(spam.get('zebra'))
None
10. 漏传参数
def diyadd(x, y, z):
return x+y+z
diyadd(1, 2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-46-7184f3f906ca> in <module>
2 return x+y+z
3
----> 4 diyadd(1, 2)
TypeError: diyadd() missing 1 required positional argument: 'z'
diyadd(1, 2, 4)
7
11. 缺失依赖库
电脑中没有相关的库
import packagename
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-48-6d7d6f569116> in <module>
----> 1 import packagename
ModuleNotFoundError: No module named 'packagename'
!pip install packagename
12. 使用了python中的关键词
如try、except、def、class、object、None、True、False等
try = 5
print(try)
File "<ipython-input-49-508e87fe2ff3>", line 1
try = 5
^
SyntaxError: invalid syntax
a = 5
print(a)
5
def = 6
print(def)
File "<ipython-input-51-c797890e9b85>", line 1
def = 6
^
SyntaxError: invalid syntax
d = 6
print(d)
6
13. 文件编码问题
import pandas as pd
df = pd.read_csv('data/twitter_sentiment.csv')
df.head()
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 7-8: invalid continuation byte
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-53-f7ee81cff3e5> in <module>
1 import pandas as pd
2
----> 3 df = pd.read_csv('data/twitter_sentiment.csv')
4 df.head()
pandas\_libs\parsers.pyx in pandas._libs.parsers._string_box_utf8()
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 7-8: invalid continuation byte
import pandas as pd
#gbk/utf-8只能解决大部分编码问题,但不能解决全部问题
df = pd.read_csv('data/twitter_sentiment.csv', encoding='gbk')
df.head()
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-55-6aa161f42239> in <module>
2
3 #gbk/utf-8只能解决大部分编码问题,但不能解决全部问题
----> 4 df = pd.read_csv('data/twitter_sentiment.csv', encoding='gbk')
5 df.head()
c:\users\thunderhit\appdata\local\programs\python\python37-32\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
674 )
675
-> 1891 self._reader = parsers.TextReader(src, **kwds)
1892 self.unnamed_cols = self._reader.unnamed_cols
1893
pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader.__cinit__()
pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._get_header()
pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows()
pandas\_libs\parsers.pyx in pandas._libs.parsers.raise_parser_error()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xbd in position 10717: illegal multibyte sequence
上面的程序会提示编码错误, 尝试encoding编码参数传入utf-8、gbk,也没有解决问题。
那怎么找到正确的编码参数呢?
import chardet
#读取为二进制数据
binary_data = open('data/twitter_sentiment.csv', 'rb').read()
#传给chardet.detect,稍等片刻
chardet.detect(binary_data)
{'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''}
import pandas as pd
df = pd.read_csv('data/twitter_sentiment.csv', encoding='Windows-1252')
df.head()
ItemID | Sentiment | SentimentText | |
---|---|---|---|
0 | 1 | 0 | is so sad for my APL frie... |
1 | 2 | 0 | I missed the New Moon trail... |
2 | 3 | 1 | omg its already 7:30 :O |
3 | 4 | 0 | .. Omgaga. Im sooo im gunna CRy. I'... |
4 | 5 | 0 | i think mi bf is cheating on me!!! ... |
14. 路径字符串写法
- Mac&Win 推荐使用
/
写法 - 如果使用
\
写法,安全起见,请换成\\
(Mac不支持\\
)
\n
\t
\d
open('data/test.txt', encoding='utf-8').read()
'章节设计\n\n第一部分 环境配置\n第二部分 快速入门python\n第三部分 网络爬虫\n第四部分 简单的文本分析\n第五部分 进阶文本分析'
open('data\test.txt', encoding='utf-8').read()
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-59-d855ed58b500> in <module>
----> 1 open('data\test.txt', encoding='utf-8').read()
OSError: [Errno 22] Invalid argument: 'data\test.txt'
open('data\\test.txt', encoding='utf-8').read()
'章节设计\n\n第一部分 环境配置\n第二部分 快速入门python\n第三部分 网络爬虫\n第四部分 简单的文本分析\n第五部分 进阶文本分析'
open('data\Test.txt', encoding='utf-8').read()
'章节设计\n\n第一部分 环境配置\n第二部分 快速入门python\n第三部分 网络爬虫\n第四部分 简单的文本分析\n第五部分 进阶文本分析'