Python基础知识
- 前言
-
- 为什么学习Python?
- Python环境、模块、软件官网
- 一、搭建Python环境
- 二、变量类型
- 三、列表、元组、字典
- 四、函数
- 五 、类
前言
为什么学习Python?
Python 本身由于库丰富,所以功能极其强大,从后台开发 Flask、AI、数据分析、爬虫… 全部都游刃有余。Python 简单易学,没有复杂的逻辑关系,相比java、C、C++对于新手、非科班或者想学一门语言感受下编程的同学很友好。
Python环境、模块、软件官网
Python官网:https://www.python.org
Pypi官网:https://pypi.org
Pycharm官网:https://www.jetbrains.com/pycharm/download/#section=windows
一、搭建Python环境
1.1 安装好Python环境后检查Python版本
windows系统在命令窗口使用python -V或python –version,如下图
linux系统默认安装Python,下图为当前计算机默认使用python版本
1.2 在不同系统输出简单的python命令
希望这能给你python学习过程中带来好运
Windows系统下
Linux系统下
二、变量类型
2.1 变量(Variable)和常量(Constant)
变量:就是将一个值(信息)赋予(即赋值Assignment)变量且这个值可以改变。因此我们说Python是动态类型语言,即可以接受其他类型的数据。全局变量:在函数外部创建的变量
局部变量:只能在函数内部使用
print('Hello World')
message = 'Hello World'
print(message)
message = 'Hello! nice to meet you'
print(message)
- 1
- 2
- 3
- 4
- 5
2.1.1 变量命名规范
- 变量名只能包含字母、数字和下划线。变量名不能以数字开头
- 变量名不能包含空格,使用下划线来分隔其中的单词
- 区分大小写
- 不要将Python关键字和函数名用作变量名
- 变量名应见名知义
- 尽量使用小写的Python变量名
2.1.2 变量命名时的名称错误
当我们故意将message写成mesage时程序报错,Python解释器指出,文件study_python01.py的第5行存在名称错误,指出mesage未找到。这有两种情况:要么没赋值,要么拼写不正确。
print('Hello World')
message = 'Hello World'
print(message)
message = 'Hello! nice to meet you'
print(mesage)
- 1
- 2
- 3
- 4
- 5
Python数据类型
内置数据类型 | |
---|---|
文本类型 | str |
数值类型 | int, float, complex |
序列类型 | list, tuple, range |
映射类型 | dict |
集合类型 | set, frozenset |
布尔类型 | bool |
二进制类型 | bytes, bytearray, memoryview |
随机数
import random
print(random.randrange(1,10))
- 1
- 2
2.2 字符串(String)
在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。
2.2.1 字符串的灵活性
字符串的灵活性可以使字符串中包含引号和撇号
print('I told my friend, "Python is becoming more and more popular!"')
print("One of Python's strengths is its diverse and supportive community")
- 1
- 2
2.2.2 使用方法修改字符串的大小写
方法是Python可对数据执行的操作。在title()中,变量后面的句点(.)让Python对变量执行方法title()指定的操作(title()以首字母大写的方式显示每个单词)。每个方法后面都跟着一对括号,这是因为方法通常需要额外的信息来完成其工作。这种信息是在括号内提供的。函数title()不需要额外的信息,因此它后面的括号是空的。
message='python java c c++'
print(message)
print(message.title())
- 1
- 2
- 3
将字符串改为全部大写或全部小写,可以使用方法upper()和方法lower()
message='Python Java C C++'
print(message.upper())
print(message.lower())
- 1
- 2
- 3
2.2.3 合并(拼接)字符串
在下面这种情况,姓和名分别存储在不同变量之中当我们需要获取姓名时可以使用加号将其合并。只能使用加号来连接字符串吗?并不是,还可以使用逗号当我们使用逗号替换加号来合并字符串时会添加空格,使用时注意两者区别。
first_name='Allen'
last_name='williams'
full_name = first_name + ' ' + last_name
print('Hello, ' + full_name.title() + '!' )
print('Hello, ' , full_name.title() , '!' )
- 1
- 2
- 3
- 4
- 5
2.2.4 使用制表符和换行符来添加空白使代码更易读
在编程中,空白泛指任何非打印字符,如空格、制表符和换行符。
print('python')
print('\tpython')
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
- 1
- 2
- 3
- 4
2.2.5 Python转义字符
转义字符 | 描述 |
---|---|
\(在行尾时) | 续行符 |
\\ | 反斜杠符号 |
\’ | 单引号 |
\” | 双引号 |
\a | 响铃 |
\b | 退格(Backspace) |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | 回车,将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成 |
\f | 换页 |
\yyy | 八进制数,y 代表 0~7 的字符,例如:\012 代表换行 |
\xyy | 十六进制数,以 \x 开头,y 代表的字符,例如:\x0a 代表换行 |
\other | 其它的字符以普通格式输出 |
2.2.6 Python字符串运算符
下表实例变量 a 值为字符串 “Hello”,b 变量值为 “Python”:
操作符 | 描述 | 实例 |
---|---|---|
+ | 字符串连接 | a + b 输出结果: HelloPython |
* | 重复输出字符串 | a*2 输出结果:HelloHello |
[ ] | 通过索引获取字符串中字符 | a[1] 输出结果 e |
[ : ] | 截取字符串中的一部分,遵循左闭右开原则,str[0:2] 是不包含第 3 个字符的 | a[1:4] 输出结果 ell |
in | 成员运算符—— 如果字符串中包含给定的字符返回 True | ‘H’ in a 输出结果 True |
not in | 成员运算符—— 如果字符串中不包含给定的字符返回 True | ‘M’ not in a 输出结果 True |
r/R | 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符 | print( r’\n’ ) print( R’\n’ ) |
% | 格式字符串 |
2.2.7 python字符串格式化符号
符号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f 和 %E 的简写 |
%p | 用十六进制数格式化变量的地址 |
2.2.8 删除空白
在不看代码的情况下,有无空白对于我们来说都是一样。但对于程序来说就是两个字符串,所以删除空白就显得很有必要。如下图:
Additional_blanks='blank'
print(Additional_blanks)
print(Additional_blanks == 'blank')# 与‘blank’进行比较相同返回True
Additional_blanks='blank '
print(Additional_blanks)
print(Additional_blanks == 'blank')
print(Additional_blanks.rstrip()) # 删除字符串末尾空格
print(Additional_blanks.rstrip() == 'blank')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
我们可以使用方法lstrip()、rstrip()和strip()删除字符串开头、末尾和两端的空白
Additional_blanks=' blank '
print(Additional_blanks.lstrip())
print(Additional_blanks.lstrip() == 'blank')
print(Additional_blanks.rstrip())
print(Additional_blanks.rstrip() == 'blank')
print(Additional_blanks.strip())
print(Additional_blanks.strip() == 'blank')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
2.2.9 使用字符串时的语法错误
当我们将‘包含在两个单引号之间时Python将无法确认字符串的结束位置
print('One of Python's strengths is its diverse and supportive community')
- 1
2.2.10 使用函数str()类型是的类型错误
当使用下面代码时Python不知道如何解读这个18,需要调用函数str(),告诉Python将非字符串值表示为字符串
age = 18
print('Happy ' + 18 + 'th birthday')
- 1
- 2
age = 18
print('Happy ' + str(18) + 'th birthday')
- 1
- 2
2.3 数字(Number)
2.3.1 整数(Int)
2.3.2 浮点数(float)
Python将带小数点的数字都称为浮点数。浮点数也可以使用科学计数法表示(3.14e2 = 3.14 x
1
0
2
10^2
102 = 314)
2.3.3复数 (complex)
复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。
2.3.4 Python 数字类型转换
int(x) 将x转换为一个整数。
float(x) 将x转换到一个浮点数。
complex(x) 将x转换到一个复数,实数部分为 x,虚数部分为 0。
complex(x, y) 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。
2.3.5 数学函数
函数 | 返回值 ( 描述 ) |
---|---|
abs(x) | 返回数字的绝对值,如abs(-1) 返回 1 |
ceil(x) | 返回数字的上入整数,如math.ceil(4.01) 返回 5 |
exp(x) | 返回e的x次幂(ex),如math.exp(2) 返回7.38905609893065 |
fabs(x) | 返回数字的绝对值,如math.fabs(-1) 返回1.0 |
floor(x) | 返回数字的下舍整数,如math.floor(4.99)返回 4 |
log(x) | 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 |
log10(x) | 返回以10为基数的x的对数,如math.log10(100)返回 2.0 |
max(x1, x2,…) | 返回给定参数的最大值,参数可以为序列 |
min(x1, x2,…) | 返回给定参数的最小值,参数可以为序列 |
modf(x) | 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示 |
pow(x, y) | x**y 运算后的值 |
round(x [,n]) | 返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数点后的位数其实准确的说是保留值将保留到离上一位更近的一端。 |
sqrt(x) | 返回数字x的平方根 |
2.3.6 随机数函数
函数 | 描述 |
---|---|
choice(seq) | 从序列的元素中随机挑选一个元素 |
randrange ([start,] stop [,step]) | 从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1 |
random() | 随机生成下一个实数,它在[0,1)范围内 |
seed([x]) | 改变随机数生成器的种子seed |
shuffle(lst) | 将序列的所有元素随机排序 |
uniform(x, y) | 随机生成下一个实数,它在[x,y]范围内 |
2.3.7 三角函数
函数 | 描述 |
---|---|
acos(x) | 返回x的反余弦弧度值 |
asin(x) | 返回x的反正弦弧度值 |
atan(x) | 返回x的反正切弧度值 |
atan2(y, x) | 返回给定的 X 及 Y 坐标值的反正切值 |
cos(x) | 返回x的弧度的余弦值 |
hypot(x, y) | 返回欧几里德范数 sqrt(xx + yy) |
sin(x) | 返回的x弧度的正弦值 |
tan(x) | 返回x弧度的正切值 |
degrees(x) | 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 |
radians(x) | 将角度转换为弧度 |
2.4 Python运算符
2.4.1 Python算术运算符
设a=3,b=2:
运算符 | 描述 | 实例 |
---|---|---|
+ | 加 | a+b输出5 |
– | 减 | a-b输出1 |
* | 乘 | a*b输出6 |
/ | 除 | a/b输出1.5 |
// | 整除 | a//b输出1 |
% | 取余 | a%b输出1 |
** | 乘方 | a**b输出9 |
2.4.2 Python比较运算符
设变量a为3,变量b为2
运算符 | 描述 | 实例 |
---|---|---|
== | 等于 | (a == b) 返回 False |
!= | 不等于 | (a != b) 返回 True |
> | 大于 | (a > b) 返回 True |
< | 小于 | (a < b) 返回 False |
>= | 大于等于 | (a >= b) 返回 True |
<= | 小于等于 | (a <= b) 返回 False |
2.4.3 Python赋值运算符
运算符 | 描述 | 实例 |
---|---|---|
= | 赋值运算符 | c = a + b将 a + b 的运算结果赋值为 c |
+= | 加法赋值运算符 | c += a 等效于 c = c + a |
-= | 减法赋值运算符 | c -= a 等效于 c = c – a |
*= | 乘法赋值运算符 | c *= a 等效于 c = c * a |
/= | 除法赋值运算符 | c /= a 等效于 c = c / a |
%= | 取模赋值运算符 | c %= a 等效于 c = c % a |
**= | 幂赋值运算符 | c **= a 等效于 c = c ** a |
//= | 取整除赋值运算符 | c //= a 等效于 c = c // a |
2.4.4 Python位运算符
设变量a为3,变量b为2
运算符 | 描述 | 实例 |
---|---|---|
& | 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 | (a & b) 输出结果 2 |
| | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1 | (a | b) 输出结果 3 |
^ | 按位异或运算符:当两对应的二进位相异时,结果为1 | (a ^ b) 输出结果 1 |
~ | 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 | ~x 类似于 -x-1 (~a ) 输出结果 -4 |
<< | 左移动运算符:运算数的各二进位全部左移若干位,由”<<“右边的数指定移动的位数,高位丢弃,低位补0 | a << 2 输出结果 12 |
>> | 右移动运算符:把”>>“左边的运算数的各二进位全部右移若干位,”>>”右边的数指定移动的位数 | a >> 2 输出结果 0 |
2.4.5 Python逻辑运算符
设变量 a 为 3, b为 2
运算符 | 逻辑表达式 | 描述 | 实例 |
---|---|---|---|
and | x and y | 布尔”与” ——如果 x 为 False,x and y 返回 x 的值,否则返回 y 的计算值 | (a and b) 返回 2 |
or | x or y | 布尔”或” —— 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值 | (a or b) 返回 3 |
not | not x | 布尔”非” ——如果 x 为 True,返回 False 。如果 x 为 False,它返回 True | not(a and b) 返回 False |
2.4.6 Python成员运算符
运算符 | 描述 | 实例 |
---|---|---|
in | 如果在指定的序列中找到值返回 True,否则返回 False | x 在 y 序列中 , 如果 x 在 y 序列中返回 True |
not in | 如果在指定的序列中没有找到值返回 True,否则返回 False | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True |
2.4.7 Python身份运算符
身份运算符用于比较两个对象的存储单元
运算符 | 描述 | 实例 |
---|---|---|
is | is 是判断两个标识符是不是引用自一个对象 | x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False |
is not | is not 是判断两个标识符是不是引用自不同对象 | x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False |
2.5.1 注释
单行注释用井号(#)表示。井号后面的内容都会被Python解释器忽略。
# 你好!朋友
print('Hello! Friend')
- 1
- 2
多行注释用三个单引号或三个双引号表示。
'''
你好!朋友
print('Hello! Friend')
'''
- 1
- 2
- 3
- 4
2.5.2 print()函数
print函数有5个参数,sep为分隔符参数,默认值是空格;end为字符串结束符号,默认值是换行符;file为输出文件参数,默认值sys.stdout是标准输出,即控制台;flush为是否刷新文件输出流缓冲区,默认不刷新。
# 字符串结束符号之间的区别,默认为换行符
print('black', 'white')
print('black', 'white', end=',')
print('black', 'white')
# 分割符之间的区别:默认为空格
print('black', 'white')
print('black', 'white', sep='|')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
2.5.3 input()函数
函数input()获取用户输入信息。当你使用函数input()时,应该准确地指出你希望用户提供什么信息。
age = input("How old are you?")
print(age)
- 1
- 2
2.6 条件、循环及其他语句
2.6.1 If语句
a = 6
b = 3
if a > b:
print("正确")
else:
print("错误")
- 1
- 2
- 3
- 4
- 5
- 6
2.6.2 For 循环
for x in range(10):
print(x)
- 1
- 2
2.6.3 while循环
while循环只要你愿意我可以一直运行,如下面代码中的i<10时将不停打印i的值直到i=10,即while后的条件成立时一直运行。
i = 1
while i < 10:
print(i)
i += 1
- 1
- 2
- 3
- 4
2.6.4 Break语句
当我想打印到5就停止时可以使用break不在执行余下代码,退出循环。
i = 1
while i < 10:
if i == 6:
break
else:
print(i)
i += 1
- 1
- 2
- 3
- 4
- 5
- 6
- 7
2.6.5 Continue语句
当我就想打印1~10里面的奇数时可以使用continue
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)
- 1
- 2
- 3
- 4
- 5
- 6
三、列表、元组、字典
3.1 列表List
列表就是一些值的有序集合,在Python中,我们用方括号[ ]来表示列表,并用逗号来分隔其中的元素。
colors = ['red', 'blue', 'green', 'black', 'white']
print(type(colors))
- 1
- 2
3.1.1 访问列表元素
列表是有序集合,因此只需将该元素的位置或索引告诉Python。列表的开头第一个列表元素索引是从0开始的,最后一个列表元素则是-1开始。
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors[0])
print(colors[1])
print(colors[-1])
print(colors[-2])
- 1
- 2
- 3
- 4
- 5
3.1.2 修改列表元素
要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
colors [0] = 'brown'
print(colors)
- 1
- 2
- 3
- 4
3.1.3 在列表中添加元素
使用方法append()在列表末尾添加元素
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
colors.append('brown')
print(colors)
- 1
- 2
- 3
- 4
使用方法insert()并指定新元素的索引和值即可在列表的任何位置添加新元素
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
colors.insert(1, 'brown')
print(colors)
- 1
- 2
- 3
- 4
3.1.4 从列表中删除元素
知道其索引使用del删除任何位置的列表元素,且使用del删除不再以任何方式使用它。
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
del colors[0]
print(colors)
- 1
- 2
- 3
- 4
方法pop()可删除列表末尾的元素,且在删除元素后还能继续使用它。
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
print(colors.pop())
print(colors)
print(colors.pop(0))
print(colors)
- 1
- 2
- 3
- 4
- 5
- 6
使用方法remove()根据值删除元素
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
colors.remove('green')
print(colors)
- 1
- 2
- 3
- 4
3.1.5 使用方法 sort()对列表进行永久性排序
使用方法sort()时下面按字母顺序排列,且永久性地修改了列表元素的排列顺序。
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
colors.sort()
print(colors)
colors.sort(reverse=True)
print(colors)
- 1
- 2
- 3
- 4
- 5
- 6
3.1.6 使用函数 sorted()对列表进行临时排序
函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
print(sorted(colors))
print(colors)
- 1
- 2
- 3
- 4
3.1.7 使用方法reverse()反转列表元素的排列顺序
reverse()不是指按与字母顺序相反的顺序排列列表元素,而是反转列表元素的排
列顺序
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors)
colors.reverse()
print(colors)
- 1
- 2
- 3
- 4
3.1.8 函数len()获取列表的长度
colors = ['red', 'blue', 'green', 'black', 'white']
print(len(colors))
- 1
- 2
3.1.9 使用列表时的索引错误
当使用以下代码时,列表索引超出列表范围时的错误提示:
colors = ['red', 'blue', 'green', 'black', 'white']
print(colors[5])
- 1
- 2
当列表不包含元素时,python返回索引报错
weather = []
print(weather[1])
- 1
- 2
3.1.9 遍历列表
下面使用for循环遍历列表并打印所有颜色
colors = ['red', 'blue', 'green', 'black', 'white']
for color in colors:
print(color)
- 1
- 2
- 3
3.1.10 缩进
python最具特色的就是使用缩进来表示代码块,同一个代码块的语句必须包含相同的缩进空格数。
3.1.11 数字列表
使用range()产生从第一个数到第二个数之间的数字(不包含第二个数的值)
numbers = list(range(1,10))
print(numbers)
- 1
- 2
简单的统计计算
numbers = list(range(1,10))
print(min(numbers))# 打印列表最小值
print(max(numbers))# 打印列表最大值
print(sum(numbers))# 打印列表总和
- 1
- 2
- 3
- 4
3.1.12 切片
所谓切片就是和range()一样,指定始索引和终止索引来创建切片。
numbers = list(range(1,10))
print(numbers[0:3])
print(numbers[:])# 输出整个列表
print(numbers[2:])# 没有终止索引输出从特定位置到列表末尾的所有元素
print(numbers[:5])# 没有始索引输出从头开始
- 1
- 2
- 3
- 4
- 5
方法 | 描述 |
---|---|
append() | 在列表的末尾添加一个元素 |
clear() | 删除列表中的所有元素 |
copy() | 返回列表的副本 |
count() | 返回具有指定值的元素数量 |
extend() | 将列表元素(或任何可迭代的元素)添加到当前列表的末尾 |
index() | 返回具有指定值的第一个元素的索引 |
insert() | 在指定位置添加元素 |
pop() | 删除指定位置的元素 |
remove() | 删除具有指定值的项目 |
reverse() | 颠倒列表的顺序 |
sort() | 对列表进行排序 |
3.2 元组(Tuple)
3.2.1 定义元组
元组:不可变的列表,使用圆括号表示逗号隔开元素,和列表一样可以通过索引访问其元素(且其元素不可更改)。
观看以下代码和效果相信你对元组会有更加清晰的认识
numbers = (1)
print(numbers)
print(type(numbers)) # 不加逗号,类型为整型
numbers = (1,)
print(numbers)
print(type(numbers)) # 加上逗号,类型为元组
- 1
- 2
- 3
- 4
- 5
- 6
当元组元素被修改将会返回类型错误:对象不支持赋值
numbers = (11,32,25,63)
numbers [0] = 1
print(numbers)
- 1
- 2
- 3
3.2.2 修改元组变量
当给存储元组的变量赋值时Python不会报告任何错误,因为给元组变量赋值是合法的
numbers = (11,32,25,63)
print(numbers)
numbers = (1,2,3,4)
print(numbers)
- 1
- 2
- 3
- 4
3.3 字典(Dictionary)
字典是一种数据结构,含有键值对。键和值之间用冒号分隔,而键—值对之间用逗号分隔。我们用大括号声明字典。
3.3.1访问字典中的值
我们可以通过指定字典名和放在方括号内的键来访问字典的值。
my_favorite = {'color' : 'white', 'teleplay': 'The Age of Awakening'}
print(my_favorite['color'])
print(my_favorite['teleplay'])
print(my_favorite)
- 1
- 2
- 3
- 4
3.3.2 使用空字典来生成键-值对
先使用一个空的花括号定义一个字典,再分行添加键-值对。
my_favorite = {}
my_favorite['color'] = 'white'
my_favorite['teleplay'] = 'The Age of Awakening'
print(my_favorite)
- 1
- 2
- 3
- 4
3.3.3 修改、删除键-值对
使用del语句指定字典名和要删除的键将相应的键—值对彻底删除
my_favorite = {'color' : 'white', 'teleplay': 'The Age of Awakening'}
print(my_favorite)
my_favorite['color'] = 'black' # 修改键-值对
print(my_favorite)
del my_favorite['color'] # 删除键-值对
print(my_favorite)
- 1
- 2
- 3
- 4
- 5
- 6
3.3.4 遍历字典
一个Python字典可能包含大量的数据,所以Python支持遍历字典的所有键—值对、键或值。
my_favorite = {
'color' : 'white',
'teleplay': 'The Age of Awakening',
'sport' : 'Badminton',
}
# items()方法遍历字典中每个键-值对
for key, value in my_favorite.items():
print("Key:" + key)
print("Value:" + value)
print()
# 在不需要使用字典值时,可以使用keys()方法遍历字典
for favorite in my_favorite.keys():
print(favorite.title())
# 因其默认遍历所有键,因此换成以下代码输出不变
for favorite in my_favorite.keys():
print(favorite.title())
# 通过方法keys()返回一个列表,我们使用以下代码检查列表是否包含’food'
if 'food' not in my_favorite.keys():
print('food, not in my_favorite')
# 遍历前对列表进行排序
for favorite in sorted(my_favorite.keys()):
print(favorite)
# 使用方法values()返回值列表
for thing in my_favorite.values():
print(thing)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
当字典中的值有重复时,我们可以使用集合(set)。集合可以看作一个列表但其元素必须唯一。
字典方法
for thing in set(my_favorite.values()):
print(thing)
- 1
- 2
方法 | 描述 |
---|---|
clear() | 删除字典中的所有元素 |
copy() | 返回字典的副本 |
fromkeys() | 返回拥有指定键和值的字典 |
get() | 返回指定键的值 |
items() | 返回包含每个键值对的元组的列表 |
keys() | 返回包含字典键的列表 |
pop() | 删除拥有指定键的元素 |
popitem() | 删除最后插入的键值对 |
setdefault() | 返回指定键的值。如果该键不存在,则插入具有指定值的键 |
update() | 使用指定的键值对字典进行更新 |
values() | 返回字典中所有值的列表 |
集合方法
方法 | 描述 |
---|---|
add() | 向集合添加元素 |
clear() | 删除集合中的所有元素 |
copy() | 返回集合的副本 |
difference() | 返回包含两个或更多集合之间差异的集合 |
difference_update() | 删除此集合中也包含在另一个指定集合中的项目 |
discard() | 删除指定项目 |
intersection() | 返回为两个其他集合的交集的集合 |
intersection_update() | 删除此集合中不存在于其他指定集合中的项目 |
isdisjoint() | 返回两个集合是否有交集 |
issubset() | 返回另一个集合是否包含此集合 |
issuperset() | 返回此集合是否包含另一个集合 |
pop() | 从集合中删除一个元素 |
remove() | 删除指定元素 |
symmetric_difference() | 返回具有两组集合的对称差集的集合 |
symmetric_difference_update() | 插入此集合和另一个集合的对称差集 |
union() | 返回包含集合并集的集合 |
update() | 用此集合和其他集合的并集来更新集合 |
四、函数
4.1.1 定义函数
我们使用关键字def告诉Python我们要定义什么样的函数,再指出函数为完成其任务需要什么信息,最后以冒号结尾。
在下面代码中,username是一个形参,形参是函数完成其工作所需的一项信息。‘OIqng’是一个实参,实参是调用函数是传递给函数的信息。
def display_user(username):
print(username)
display_user('OIqng')
- 1
- 2
- 3
编写函数时,我们还可以给每个形参指定默认值。给形参指定 默认值时,等号两边不要空格。
def display_user(username='OIqng'):
print(username)
display_user()
display_user('Oiqng')
- 1
- 2
- 3
- 4
4.1.2 位置实参
函数调用时每个实参都关联一个形参,这种基于实参顺序的关联方式称为位置实参。注意函数中调用实参的顺序与形参一致。
def describe_favorite(favorite_type, favorite_thing):
print("My favorite type is " + favorite_type)
print("My favorite thing is " + favorite_thing)
describe_favorite('color', 'white')
describe_favorite('teleplay', 'The Age of Awakening')
- 1
- 2
- 3
- 4
- 5
4.1.3 关键字实参
关键字实参是传递给函数的名称-值对。因其在实参中将名称和值关联起来,使用函数传递时不用考虑调用的实参顺序。
def describe_favorite(favorite_type, favorite_thing):
print("My favorite type is " + favorite_type)
print("My favorite thing is " + favorite_thing)
describe_favorite(favorite_type='color', favorite_thing='white')
describe_favorite(favorite_type='teleplay', favorite_thing='The Age of Awakening')
- 1
- 2
- 3
- 4
- 5
4.1.4 返回值
函数返回的值被称为返回值。在函数中,使用return语句将值返回到调用函数的代码行。
def display_user(username):
return username
name = display_user('OIqng')
print(name)
- 1
- 2
- 3
- 4
4.1.5 将实参变为可选
当我们为favorite_game的默认值指定一个空字符串时,当用户没有提供这个值时不使用这个实参。
def get_my_favorite(favorite_color, favorite_teleplay, favorite_game=''):
print("My favorite color is " + favorite_color)
print("My favorite teleplay is " + favorite_teleplay)
if favorite_game:
print("My favorite game is " + favorite_game)
else:
print()
get_my_favorite(favorite_color='white', favorite_teleplay='The Age of Awakening')
get_my_favorite(favorite_color='white', favorite_teleplay='The Age of Awakening', favorite_game='Gode Combat')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
4.1.6 返回字典
def my_favorite(favorite_color, favorite_teleplay):
favorite = {'color': favorite_color, 'teleplay': favorite_teleplay}
return favorite
print(my_favorite('white', 'The Age of Awakening'))
- 1
- 2
- 3
- 4
4.1.7 传递列表
我们通过使用名为greet_user()的函数,将列表传递给函数,提高列表的效率。
def greet_user(names):
for name in names:
message = "Good Morning, " + name.title() + "! "
print(message)
usernames = ['OIqng', 'Oiqng']
greet_user(usernames)
- 1
- 2
- 3
- 4
- 5
- 6
4.1.8 传递任意数量的实参
我们使用形参为*toppings收集任意数量的实参。
def greet_user(*toppings):
print(toppings)
greet_user('OIqng')
greet_user('OIqng', 'Oiqng')
- 1
- 2
- 3
- 4
4.1.9 结合使用位置实参和任意数量实参
我们想让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放到最后。
def book_ticket(location, *toppings):
print("Select your location : " + location + "Select your ticket :")
for topping in toppings:
print("- " + topping)
book_ticket('Hangzhou', 'train')
book_ticket('Hangzhou', 'train', 'airline')
- 1
- 2
- 3
- 4
- 5
- 6
4.1.10 使用任意数量的关键字实参
当不知道传递给函数的会是什么样的信息时,我们可将函数编写 成能够接受任意数量的键-值对——调用语句提供多少就接受多少。
def build_profile(name, age, **user_info):
profile = {} # 创建名为profile空字典
profile['name'] = name
profile['age'] = age
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('OIqng', 19,
location='Hangzhou',
field='physics')
print(user_profile)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
4.1.11 PIP
PIP是什么?
PIP是python包或模块的包管理器
包(Package)是什么?
包包含模块所需的所有文件,模块是包含在项目中的代码库
在命令行界面使用pip –version检查是否安装PIP
下载包
使用pip install camelacase下载包
删除包
使用pip uninstall camelcase删除包
列出包
使用pip list列出系统上安装的所有软件包
五 、类
类名命名时类名中的每个单词的首字母都大写,实例名和模块名都小写。
Python面向对象编程
基于类创建对象,实例化
5.1.1 创建、使用Cat类
class Cat():
'''猫的模拟小尝试'''
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(self.name.title() + " is eating now")
def sleep(self):
print(self.name.title() + " is sleeping now")
my_cat = Cat('Maily', 3)
print("My cat name is " + my_cat.name.title() + ".")
print("My cat age is " + str(my_cat.age) + ".")
# 调用方法
my_cat.eat()
my_cat.sleep()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
5.1.2 修改属性的值
class Cat():
'''猫的模拟小尝试'''
def __init__(self, name):
self.name = name
self.age = 1
def update_age(self, age):
self.age = age
if age >= self.age:
self.age = age
else:
print("You can't change ")
def increment_age(self, age):
self.age += age
my_cat = Cat('Maily')
print("My cat name is " + my_cat.name.title() + ".")
print("My cat age is " + str(my_cat.age) + ".")
# 直接修改属性的值
my_cat.age = 3
print("My cat age is " + str(my_cat.age) + ".")
# 通过方法修改属性的值 无需访问属性,也可将值传递给一个方法
my_cat.update_age(4)
print("My cat age is " + str(my_cat.age) + ".")
# 通过方法进行递增
my_cat.increment_age(1)
print("My cat age is " + str(my_cat.age) + ".")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
5.1.3 继承
一个类继承另一个类时,它将获得另一个类的所有属性和方法:原有的类称为父类,新类称为子类。子类继承了其父类的所有属性和方法,同时还可定义自己的属性和方法。
5.1.4 读取文件
open() 函数有两个参数:文件名和模式。
有四种打开文件的不同方法(模式):
- “r” – 读取 – 默认值。打开文件进行读取,如果文件不存在则报错。
- “a” – 追加 – 打开供追加的文件,如果不存在则创建该文件。
- “w” – 写入 – 打开文件进行写入,如果文件不存在则创建该文件。
- “x” – 创建 – 创建指定的文件,如果文件存在则返回错误。
此外,还可指定文件是作为二进制还是文本模式进行处理。
- “t” – 文本 – 默认值。文本模式。
- “b” – 二进制 – 二进制模式(例如图像)。
with open('number.txt') as file_object:
contents = file_object.read()
print(contents)
- 1
- 2
- 3
5.1.5 逐行读取
当我们使用循环来遍历文件中的每一行时发现每打印一行就会出现一行空白行。思考:为什么会出现空白行呢?还记不记得print语句的end的默认值是什么,没错就是换行符。所以要消除这些换行符,可在print语句中使用rstrip()
f = open('number.txt', "r")
print(f.readline())# readline()读取行
f.close()# 关闭文件
- 1
- 2
- 3
filename = 'number.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
- 1
- 2
- 3
- 4
filename = 'number.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
- 1
- 2
- 3
- 4
5.1.6 写入文件
写入文件参数
- “a” – 追加 – 会追加到文件的末尾
- “w” – 写入 – 会覆盖任何已有的内容
filename = 'demo.txt'
with open(filename, 'w') as file_object:
file_object.write("I love cat.\n")
file_object.write("I love see cat sleep.\n")
- 1
- 2
- 3
- 4
当我们只想添加内容,而不是覆盖原有的内容,我们可以附加模式打开文件
filename = 'demo.txt'
with open(filename, 'w') as file_object:
file_object.write("I love cat.\n")
file_object.write("I love see cat sleep.\n")
with open(filename, 'a') as file_object:
file_object.write("I also love eat delicious food.\n")
file_object.write("I also love read book.\n")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
5.1.9 删除文件
import os
# 删除文件
os.remove("number.txt")
# 删除空文件夹
os.rmdir("my")
- 1
- 2
- 3
- 4
- 5
5.1.8 异常
异常:管理程序执行期间发生的错误
ZeroDivisionError异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
- 1
- 2
- 3
- 4
try-except-else代码块
filename = 'alic.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
5.1.10 存储数据
我们使用json.dump()和json.load()来存储数据,JSON(JavaScript Object Notation):json.dump()接受两个实参:存储的数据和存储数据的文件对象;json.load()加载存储的信息
import json
numbers = [1, 2, 3, 3, 1]
filename = 'numbers.json'
# 使用json.dump()将列表存储到numbers.json文件
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
# 使用json.load()将列表读取到内存中
with open('numbers.json') as f_obj:
numbers = json.load(f_obj)
print(numbers)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
5.1.11 重构
重构:对代码进一步优化——将代码划分为一系列完成具体工作的函数
unittest Module中的断言方法
方法 | 用途 |
---|---|
assertEqual(a, b) | 核实a == b |
assertNotEqual(a, b) | 核实a != b |
assertTrue(x) | 核实x为True |
assertFalse(x) | 核实x为False |
assertIn(item, list) | 核实item在list中 |
assertNotIn(item, list) | 核实item不在list中 |