# 计算机组成
学习目标
计算机组成
Python 简介 学习目标
了解 Python
Python 的应用领域
Python 的版本
Python 介绍 Python 是时下最流行、最火爆的编程语言之⼀,具体原因如下:
简单、易学,适应人群广泛
python 内库和第三方库
内库:python 底层封装好的模块 比如:unittest 、 os
第三方库:不是 python 底层封装好的模块, 比如:pytest openpyxl htmltestrunner
免费、开源
应用领域广泛
Python 版本 小结
Python 优点:
Python 学习版本:3.7
开发环境搭建 学习目标
Python 的安装
PyCharm 的作⽤
下载安装 PyCharm
PyCharm 的基本使用
PyCharm 的基本设置
Python 解析器的安装 学习目标
解释器器的作用
下载 Python 解释器
安装 Python 解释器
解释器的作用
Python 解释器作用:运行文件
Python 解释器种类
CPython,C 语言开发的解释器[官方],应用广泛的解释器。
IPython,基于 CPython 的⼀种交互式解释器。
其他解释器
PyPy,基于 Python 语言开发的解释器。
Jython,运行在 Java 平台的解释器,直接把 Python 代码编译成 Java 字节码执行。
IronPython,运行在微软.Net 平台上的 Python 解释器,可以直接把 Python 代码编译成.Net 的字节码。
课程中使用的解释器:CPython
安装 Python 解释器
双击可执行文件 — 勾选[pip] – [Next] – [勾选添加环境变量] – [Install],按提示操作即可。
小结
PyCharm 的作用
PyCharm 是⼀种 Python IDE(集成开发环境),带有一整套可以帮助用户在使用 Python 语言开发时提⾼其效率的工具,内部集成的功能如下:
Project 管理
智能提示
语法⾼高亮
代码跳转
调试代码
解释代码(解释器器)
框架和库
……
PyCharm 分为专业版(professional)和社区版(community)
PyCharm 的下载和安装 下载
注意:这里选择 Community(社区版)下载,专业版是收费版本,社区版可以满足我们基础编程需求。
安装
双击安装包 – [运行] – [允许你应用更改设备]: [是] – [Next] – [选择安装位置] – [Next] – [Install] –[Finish]。
PyCharm 基本使用 新建项⽬
打开 PyCharm – [Create New Project] – 选择项目根目录和解释器器版本 – [Create],即可完成新建⼀个项目。
新建文件并书写代码
项⽬根⽬录或根目录内部任意位置 — 右键 – [New] – [Python File] – 输⼊⽂件名 – [OK]
如果是将来要上传到服务器器的文件,那么文件名切记不能用中⽂。
双击打开文件,并书写⼀个最简单的 Python 代码:
运行文件
文件打开状态 – 空白位置 — 右键 – Run – 即可调出 Pycharm 的控制台输出程序结果。
PyCharm 的基本设置
[file] – [Settings]/[Default Settings]。
修改主题
[Appearance & Behavior] – [Appearance]
Theme:修改主题
Name:修改主题字体
Size:修改主题字号
修改代码文字格式
[Editor] – [Font]
Font:修改字体
Size:修改字号
Line Spacing:修改行间距
修改解释器器
[Project: 项目名称] – [Project Interpreter] – [设置图标] – [Add] – 浏览到目标解释器器 – [OK] –[OK]。
项目管理
[File] – [Open] – 浏览选择目标项目根目录 – [OK] – 选择打开项目方式。
打开项目的方式共三种,分别如下:
This Window
New Window
在新窗⼝打开,则打开两次 PyCharm,每个 PyCharm 负责⼀个项目。
关闭项目
[File] – [Close Project]/[Close Projects in current window]
小结
PyCharm 新建文件
项目管理空⽩白位置 — 右键 – New – PythonFile
运行文件
修改代码文字格式
[file] – [Settings]/[Default Settings] – [Editor] – [Font]
注释 学习目标
注释的作用
通过⽤自己熟悉的语言,在程序中对某些代码进行标注说明,这就是注释的作用,能够大增强程序的可读性。
注释的分类及语法
注释分为两类:单行注释 和 多行注释。
三对单引号 ''' 我是注释 '''
或者三对双引号 """ 我是注释 """
快捷键: ctrl + /
解释器不执行任何的注释内容
单行注释
1 2 3 print ('hello world' )print ('hello Python' )
多行注释
可以注释多行内容,一般用在注释一段代码的情况, 语法如下:
1 2 3 4 5 6 7 8 9 10 11 """ 第一行注释 第二行注释 第三行注释 """ ''' 注释1 注释2 注释3 '''
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 """ 下⾯三行都是输出的作用,输出内容分别是: hello Python hello itcast hello itheima """ print ('hello Python' )print ('hello itcast' )print ('hello itheima' )''' 下⾯三⾏都是输出的作⽤,输出内容分别是: hello Python hello itcast hello itheima ''' print ('hello Python' )print ('hello itcast' )print ('hello itheima' )
小结
注释的作用
用⼈类熟悉的语言对代码进行解释说明,⽅便后期维护。
注释的分类
单行: # 注释内容
,快捷键ctrl+/
多行: """ 注释内容 """
或 ''' 注释内容 '''
解释器不执⾏注释的内容
变量 学习目标
变量的作用
举例体验:我们去图书馆读书,怎么样快速找到⾃自己想要的书籍呢?是不是管理员提前将书放到固定位置,并把这个位置进行了编号,我们只需要在图书馆中按照这个编号查找指定的位置就能找到想要的书籍。
这个编号其实就是把书籍存放的书架位置起了⼀个名字,⽅便后期查找和使用。
程序中,数据都是临时存储在内存中,为了更快速的查找或使用这个数据,通常我们把这个数据在内存中存储之后定义⼀个名称,这个名称就是变量。
变量就是⼀个存储数据的的时候当前数据所在的内存地址的名字而已。
定义变量
标识符
标识符命名规则是 Python 中定义各种名字的时候的统⼀规范,具体如下:
由数字、字母、下划线组成
不能数字开头
不能使用内置关键字
严格区分⼤小写
常见的关键字 :
1 2 3 False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield
命名习惯
⻅名知义。
⼤驼峰:即每个单词⾸首字母都大写,例如: MyName 。
⼩驼峰:第⼆个(含)以后的单词⾸首字⺟大写,例如: myName 。
下划线:例如: my_name 。
使用变量 1 2 3 4 5 my_name = 'TOM' print (my_name)schoolName = '⿊马程序员' print (schoolName)
Debug 工具 认识 bug
所谓 bug,就是程序中的错误。如果程序有错误,需要程序员排查问题,纠正错误。
Debug 工具
Debug 工具是 PyCharm IDE 中集成的用来调试程序的工具,在这里程序员可以查看程序的执行细节和流程或者调解 bug。
Debug 工具使⽤步骤:
打断点
断点位置
⽬标要调试的代码块的第⼀行代码即可,即一个断点即可。
打断点的方法
Debug 调试
打成功断点后,在文件内部任意位置 — 右键 – Debug’⽂件名’ — 即可调出 Debug ⼯具⾯板 – 单击 StepOver/F8,即可按步执行代码。
Debug 输出面板分类
数据类型 认识数据类型
在 Python ⾥为了应对不同的业务需求,也把数据分为不同的类型。
检测数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 a = 1 print (type (a)) b = 1.1 print (type (b)) c = True print (type (c)) d = '12345' print (type (d)) e = [10 , 20 , 30 ] print (type (e)) f = (10 , 20 , 30 ) print (type (f)) h = {10 , 20 , 30 } print (type (h)) g = {'name' : 'TOM' , 'age' : 20 } print (type (g))
小结
标识符
由数字、字⺟母、下划线组成
不能数字开头
不能使用内置关键字
严格区分大小写
数据类型
整型:int
浮点型:float
字符串:str
布尔型:bool
元组:tuple
集合:set
字典:dict
输出 学习目标
输出
1 2 3 4 5 6 7 8 print ('hello Python' )age = 18 print (age)
格式化输出
格式化符号
格式符号
转换
%s
字符串
%d
有符号的十进制整数
%f
浮点数
%c
字符
%u
⽆符号十进制整数
%o
八进制整数
%x
十六进制整数(小写 ox)
%X
十六进制整数(⼤写 OX)
%e
科学计数法(⼩写’e’)
%E
科学计数法(大写’E’)
%g
%f 和%e 的简写
%G
%f 和%E 的简写
技巧
%06d
,表示输出的整数显示位数,不足以 0 补全,超出当前位数则原样输出
%.2f
,表示小数点后显示的小数位数。
格式化字符串除了%s
,还可以写为f'{表达式}'
f-格式化字符串
是 Python3.6 中新增的格式化⽅法,该方法更简单易读。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 age = 18 name = 'TOM' weight = 75.5 student_id = 1 print ('我的名字是%s' % name)print ('我的学号是%4d' % student_id)print ('我的体重是%.2f公⽄斤' % weight)print ('我的名字是%s,今年%d岁了' % (name, age))print ('我的名字是%s,明年%d岁了' % (name, age + 1 ))print (f'我的名字是{name} , 明年{age + 1 } 岁了' )
转义字符
\n
:换行。
\t
:制表符,⼀个 tab 键(4 个空格)的距离。
结束符
想⼀想,为什么两个 print 会换行输出?
在 Python 中,print()
默认⾃带 end="\n"
这个换行结束符,所以导致每两个 print 直接会换行展示,⽤户可以按需求更改结束符。
1 print ('输出的内容' , end="\n" )
小结
格式化符号
%s
:格式化输出字符串
%d
:格式化输出整数
%f
:格式化输出浮点数
f-字符串
转义字符
print 结束符
输入 学习目标
输入
在 Python 中,程序接收用户输入的数据的功能即是输入。
输入的语法
输入的特点
当程序执行到 input ,等待用户输入,输入完成之后才继续向下执行。
在 Python 中, input 接收⽤户输入后,一般存储到变量,方便便使用。
在 Python 中, input 会把接收到的任意用户输入的数据都当做字符串处理。
1 2 3 4 5 password = input ('请输入您的密码:' ) print (f'您输入的密码是{password} ' )print (type (password))
小结
输入功能
输入的特点
一般将 input 接收的数据存储到变量
input 接收的任何数据默认都是字符串数据类型
数据类型转换 学习目标
转换数据类型的作用
问:input()接收用户输入的数据都是字符串类型,如果⽤户输入 1,想得到整型该如何操作?
答:转换数据类型即可,即将字符串类型转换成整型。
转换数据类型的函数
函数
说明
int(x [,base ])
将 x 转换为⼀个整数
float(x )
将 x 转换为⼀个浮点数
complex(real [,imag ])
创建⼀个复数,real 为实部,imag 为虚部
str(x )
将对象 x 转换为字符串
repr(x )
将对象 x 转换为表达式字符串
eval(str )
用来计算在字符串中的有效 Python 表达式,并返回⼀个对象
tuple(s )
将序列 s 转换为一个元组
list(s )
将序列 s 转换为⼀个列表
chr(x )
将⼀个整数转换为一个 Unicode 字符
ord(x )
将一个字符转换为它的 ASCII 整数值
hex(x )
将一个整数转换为一个⼗十六进制字符串
oct(x )
将⼀个整数转换为一个⼋八进制字符串
bin(x )
将⼀个整数转换为一个⼆二进制字符串
需求:input 接收用户输入,用户输入“1”,将这个数据 1 转换成整型:
1 2 3 4 5 6 7 8 9 10 11 num = input ('请输入您的幸运数字:' ) print (f"您的幸运数字是{num} " )print (type (num))print (type (int (num)))
案例 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 num1 = 1 print (float (num1))print (type (float (num1)))num2 = 10 print (type (str (num2)))list1 = [10 , 20 , 30 ] print (tuple (list1))print (type (tuple (list1)))t1 = (100 , 200 , 300 ) print (list (t1))print (type (list (t1)))str1 = '10' str2 = '[1, 2, 3]' str3 = '(1000, 2000, 3000)' print (type (eval (str1)))print (type (eval (str2)))print (type (eval (str3)))
小结
转换数据类型常用的函数
int()
float()
str()
list()
tuple()
eval()
运算符 学习目标
运算符的分类
算数运算符
赋值运算符
复合赋值运算符
⽐比较运算符
逻辑运算符
算数运算符
运算符
描述
实例
+
加
1 + 1 输出结果为 2
-
减
1 - 1 输出结果为 0
*
乘
2 * 2 输出结果为 4
/
除
10 / 2 输出结果为 5
//
整除
9 // 4 输出结果为 2
%
取余
9 % 4 输出结果为 1
**
指数
2 *_ 4 输出结果为 16,即 2 _ 2 _ 2 _ 2
()
小括号
小括号用来提⾼高运算优先级,即 (1 + 2) * 3 输出结果为 9
注意:
混合运算优先级顺序: ()
⾼高于 **
⾼高于 *
/
//
%
⾼高于 +
-
赋值运算符
运算符
描述
实例
=
赋值
将 =
右侧的结果赋值给等号左侧的变量
1 2 3 4 5 num1, float1, str1 = 10 , 0.5 , 'hello world' print (num1) print (float1) print (str1)
1 2 3 a = b = 10 print (a) print (b)
复合赋值运算符
运算符
描述
实例
+=
加法赋值运算符
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
1 2 3 4 5 a = 100 a += 1 print (a)
1 2 3 4 5 c = 10 c += 1 + 2 print (c)
比较运算符
运算符
描述
实例
==
判断相等。如果两个操作数的结果相等,则条件结果为真(True),否则条件结果为假(False)
如 a=3,b=3,则(a == b) 为 True
!=
不等于 。如果两个操作数的结果不相等,则条件为真(True),否则条件结果为假(False)
如 a=3,b=3,则(a == b) 为 True 如 a=1,b=3,则 (a != b) 为 True
>
运算符左侧操作数结果是否⼤于右侧操作数结果,如果⼤于,则条件为真,否则为假
如 a=7,b=3,则(a > b) 为 True
<
运算符左侧操作数结果是否⼩于右侧操作数结果,如果小于,则条件为真,否则为假
如 a=7,b=3,则(a < b) 为 False
>=
运算符左侧操作数结果是否⼤于等于右侧操作数结果,如果大于,则条件为真,否则为假
如 a=7,b=3,则(a < b) 为 False 如 a=3,b=3,则(a >= b) 为 True
<=
运算符左侧操作数结果是否小于等于右侧操作数结果,如果⼩小于,则条件为真,否则为假
如 a=3,b=3,则(a <= b) 为 True
1 2 3 4 5 6 7 8 9 a = 7 b = 5 print (a == b) print (a != b) print (a < b) print (a > b) print (a <= b) print (a >= b)
逻辑运算符
运算符
逻辑表达式
描述
实例
and
x and y
布尔”与”:如果 x 为 False,x and y 返回 False,否则它返回 y 的值。
True and False, 返回 False。
or
x or y
布尔”或”:如果 x 是 True,它返回 True,否则它返回 y 的值。
False or True, 返回 True。
not
not x
布尔”非”:如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。
not True 返回 False, not False 返回 True
1 2 3 4 5 6 7 8 a = 1 b = 2 c = 3 print ((a < b) and (b < c)) print ((a > b) and (b < c)) print ((a > b) or (b < c)) print (not (a > b))
拓展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 a = 0 b = 1 c = 2 print (a and b) print (b and a) print (a and c) print (c and a) print (b and c) print (c and b) print (a or b) print (a or c) print (b or c)
总结
算数运算的优先级
混合运算优先级顺序: ()
高于 **
⾼高于 *
/
//
%
⾼高于 + -
赋值运算符
复合赋值运算符
+=
-=
优先级
先算复合赋值运算符右侧的表达式
再算复合赋值运算的算数运算
最后算赋值运算
比较运算符
判断相等: ==
大于等于: >=
小于等于:<=
不等于: !=
逻辑运算符
if 条件语句 学习目标
条件语句句作用
if 语法
if…else…
多重判断
if 嵌套
条件语句
假设⼀个场景:
同学们这个年龄去过网吧吗?
去网吧进门想要上网必须做的一件事是做什么?(考虑重点)
为什么要把身份证给工作⼈员?
是不是就是为了判断是否成年?
是不是如果成年可以上网?如果不成年则不允许上网?
其实这⾥所谓的判断就是条件语句,即条件成立执行某些代码,条件不成⽴则不执⾏这些代码。
if 语法 语法 1 2 3 4 if 条件: 条件成⽴立执行的代码1 条件成⽴立执行的代码2 ......
1 2 3 4 5 6 if True : print ('条件成⽴立执行的代码1' ) print ('条件成⽴立执行的代码2' ) print ('我是无论条件是否成⽴立都要执行的代码' )
案例
需求分析:如果用户年龄大于等于 18 岁,即成年,输出”已经成年,可以上网”。
1 2 3 4 5 age = 20 if age >= 18 : print ('已经成年,可以上网' ) print ('系统关闭' )
新增需求:用户可以输出⾃己的年龄,然后系统进行判断是否成年,成年则输出”您的年龄是’⽤户输入的年龄’,已经成年,可以上网”。
1 2 3 4 5 6 7 age = int (input ('请输入您的年龄:' )) if age >= 18 : print (f'您的年龄是{age} ,已经成年,可以上网' ) print ('系统关闭' )
if…else…
作⽤:条件成⽴立执行 if 下方的代码; 条件不成立执行 else 下方的代码。
思考:网吧上网的实例,如果成年,允许上网,如果不成年呢?是不是应该回复用户不能上网?
语法 1 2 3 4 5 6 7 8 if 条件: 条件成⽴立执行的代码1 条件成⽴立执行的代码2 ...... else : 条件不成⽴立执行的代码1 条件不成⽴立执行的代码2 ......
1 2 3 4 5 6 7 8 age = int (input ('请输入您的年龄:' )) if age >= 18 : print (f'您的年龄是{age} ,已经成年,可以上网' ) else : print (f'您的年龄是{age} ,未成年,请自行回家写作业' ) print ('系统关闭' )
注意:如果某些条件成立执行了相关的代码,那么其他的情况的代码解释器根本不会执行。
多重判断
思考:中国合法工作年龄为 18-60 岁,即如果年龄⼩小于 18 的情况为童工,不合法;如果年龄在 18-60 岁之间为合法工龄;大于 60 岁为法定退休年龄。
语法 1 2 3 4 5 6 7 8 9 10 11 if 条件1 : 条件1 成⽴立执行的代码1 条件1 成⽴立执行的代码2 ...... elif 条件2 : 条件2 成⽴立执行的代码1 条件2 成⽴立执行的代码2 ...... ...... else : 以上条件都不成⽴立执行执行的代码
多重判断也可以和 else 配合使用。⼀般 else 放到整个 if 语句的最后,表示以上条件都不成立的时候执行的代码。
实例 1 2 3 4 5 6 7 age = int (input ('请输入您的年龄:' )) if age < 18 : print (f'您的年龄是{age} ,童工⼀枚' ) elif age >= 18 and age <= 60 : print (f'您的年龄是{age} ,合法工龄' ) elif age > 60 : print (f'您的年龄是{age} ,可以退休' )
拓展: age >= 18 and age <= 60
可以化简为 18 <= age <= 60
。
if 嵌套
思考:坐公交:如果有钱可以上车,没钱不能上车;上车后如果有空座,则可以坐下;如果没空座,就要站着。怎么书写程序?
语法 1 2 3 4 5 6 7 if 条件1 : 条件1 成⽴立执行的代码 条件1 成⽴立执行的代码 if 条件2 : 条件2 成⽴立执行的代码 条件2 成⽴立执行的代码
注意:条件 2 的 if 也是出于条件 1 的缩进关系内部。
案例
1 2 3 4 5 6 7 8 9 10 11 12 """ 1. 如果有钱,则可以上车 2. 上⻋后,如果有空座,可以坐下 上⻋后,如果没有空座,则站着等空座位 如果没钱,不能上车 """ money = 1 if money == 1 : print ('⼟土豪,不差钱,顺利利上车' ) else : print ('没钱,不能上车,追着公交车跑' )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 """ 1. 如果有钱,则可以上车 2. 上车后,如果有空座,可以坐下 上车后,如果没有空座,则站着等空座位 如果没钱,不能上车 """ money = 1 seat = 0 if money == 1 : print ('土豪,不差钱,顺利上车' ) if seat == 1 : print ('有空座,可以坐下' ) else : print ('没有空座,站等' ) else : print ('没钱,不能上车,追着公交车跑' )
if 嵌套执行流程
应用_猜拳游戏
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 27 28 """ 提示:0-⽯石头,1-剪⼑刀,2-布 1. 出拳 玩家输入出拳 电脑随机出拳 2. 判断输赢 玩家获胜 平局 电脑获胜 """ import randomcomputer = random.randint(0 , 2 ) print (computer)player = int (input ('请出拳:0-⽯石头,1-剪⼑刀,2-布:' )) if ((player == 0 ) and (computer == 1 ) or ((player == 1 ) and (computer == 2 ) or ((player == 2 ) and (computer == 0 )): print ('玩家获胜' ) elif player == computer: print ('平局' ) else : print ('电脑获胜' )
三目运算符
三目运算符也叫三元运算符或三元表达式。
语法如下:
条件成⽴立执行的表达式 if 条件 else 条件不成立执行的表达式
1 2 3 4 a = 1 b = 2 c = a if a > b else b print (c)
总结
1 2 3 4 if 条件: 条件成⽴立执⾏的代码 else : 条件不成⽴立执行的代码
1 2 3 4 5 6 if 条件1 : 条件1 成⽴立执行的代码 elif 条件2 : 条件2 成⽴立执行的代码 else : 以上条件都不成⽴立执⾏的代码
1 2 3 4 5 if 条件1 : 条件1 成⽴立执行的代码 if 条件2 : 条件2 成⽴立执行的代码 ....
1 条件成⽴立执行的表达式 if 条件 else 条件不成⽴立执行的表达式
循环 while 循环 学习目标
了解循环
while 语法【重点】
while 应用
break 和 continue
while 循环嵌套【重点】
while 循环嵌套应用【难点】
for 循环
循环简介 循环的作⽤
思考:假如我有个⼥女女朋友,有⼀天我们闹⽭矛盾生⽓气了,⼥女女朋友说:道歉,说 100 遍“媳妇⼉儿,我错了”。这个时候程序员会怎么做?
答:100 遍 print(‘媳妇⼉儿,我错了’)
思考:复制粘贴 100 次吗?
答:重复执行 100 次⼀样的代码,程序中循环即可
循环的作用:让代码更⾼效的重复执行 。
循环的分类
在 Python 中,循环分为 while 和 for 两种,最终实现效果相同。
while 的语法 1 2 3 4 while 条件: 条件成⽴立重复执行的代码1 条件成⽴立重复执行的代码2 ......
需求:复现重复执行 100 次 print(‘媳妇⼉儿,我错了’) (输出更简洁一些,我们这里设置 5 次)。
分析:初始值是 0 次,终点是 5 次,重复做的事情输出“媳妇儿, 我错了”。
1 2 3 4 5 6 7 i = 0 while i < 5 : print ('媳妇⼉儿,我错了' ) i += 1 print ('任务结束' )
while 的应用 计算 1-100 累加和
分析:1-100 的累加和,即 1 + 2 + 3 + 4 +….,即前两个数字的相加结果 + 下⼀个数字( 前⼀个数字 +1)。
1 2 3 4 5 6 7 8 i = 1 result = 0 while i <= 100 : result += i i += 1 print (result)
注意:为了验证程序的准确性,可以先改小数值,验证结果正确后,再改成 1-100 做累加。
计算 1-100 偶数累加和
分析:1-100 的偶数和,即 2 + 4 + 6 + 8….,得到偶数的方法如下:
偶数即是和 2 取余结果为 0 的数字,可以加入条件语句句判断是否为偶数,为偶数则累加
初始值为 0 / 2 , 计数器器每次累加 2
1 2 3 4 5 6 7 8 9 10 i = 1 result = 0 while i <= 100 : if i % 2 == 0 : result += i i += 1 print (result)
1 2 3 4 5 6 7 8 9 i = 0 result = 0 while i <= 100 : result += i i += 2 print (result)
break 和 continue
break 和 continue 是循环中满足⼀定条件退出循环的两种不同方式。
举例例:⼀共吃 5 个苹果,吃完第⼀个,吃第二个…,这里”吃苹果”的动作是不是重复执行?
情况⼀:如果吃的过程中,吃完第三个吃饱了,则不需要再吃第 4 个和第五个苹果,即是吃苹果的动作停止,这里就是 break 控制循环流程,即终⽌此循环。
情况⼆:如果吃的过程中,吃到第三个吃出⼀个⼤⾍子…,是不是这个苹果就不吃了,开始吃第四个苹果,这⾥就是 continue 控制循环流程,即退出当前⼀次循环继⽽执⾏下⼀次循环代码。
1 2 3 4 5 6 7 8 i = 1 while i <= 5 : if i == 4 : print (f'吃饱了不吃了' ) break print (f'吃了第{i} 个苹果' ) i += 1
1 2 3 4 5 6 7 8 9 10 i = 1 while i <= 5 : if i == 3 : print (f'大⾍虫子,第{i} 个不吃了' ) i += 1 continue print (f'吃了第{i} 个苹果' ) i += 1
while 循环嵌套 应用场景
故事梗概:有天女朋友⼜⽣⽓了,惩罚:说 3 遍“媳妇⼉儿, 我错了”,这个程序是不是循环即可?但如果女朋友说:还要刷今天晚饭的碗,这个程序怎么书写?
1 2 3 while 条件: print ('媳妇⼉儿, 我错了' ) print ('刷晚饭的碗' )
但如果女朋友还是⽣气,把这套惩罚要连续 3 天都执行,有如何书写程序?
1 2 3 4 while 条件: while 条件: print ('媳妇⼉儿, 我错了' ) print ('刷晚饭的碗' )
语法 1 2 3 4 5 6 while 条件1 : 条件1 成⽴立执⾏的代码 ...... while 条件2 : 条件2 成⽴立执行的代码 ......
总结:所谓 while 循环嵌套,就是一个 while ⾥面嵌套一个 while 的写法,每个 while 和之前的基础语法是相同的。
案例 1 2 3 4 5 6 7 8 9 j = 0 while j < 3 : i = 0 while i < 3 : print ('媳妇⼉儿,我错了' ) i += 1 print ('刷晚饭的碗' ) print ('一套惩罚结束----------------' ) j += 1
理解执⾏流程
当内部循环执⾏完成之后,再执⾏下一次外部循环的条件判断。
while 循环嵌套应用 打印星号(正方形)
1 2 3 4 5 ***** ***** ***** ***** *****
代码 :
分析:⼀行行输出 5 个星号,重复打印 5 ⾏
1 2 3 4 5 6 7 8 9 10 11 12 j = 0 while j <= 4 : i = 0 while i <= 4 : print ('*' , end='' ) i += 1 print () j += 1
打印星号(三角形)
代码
分析:一行输出星星的个数和⾏号是相等的,每行:重复打印行号数字个星号,将打印行星号的命令重复执行 5 次实现打印 5 行。
1 2 3 4 5 6 7 8 9 10 11 12 j = 0 while j <= 4 : i = 0 while i <= j: print ('*' , end='' ) i += 1 print () j += 1
九九乘法表
1 2 3 4 5 6 7 8 9 10 j = 1 while j <= 9 : i = 1 while i <= j: print (f'{i} *{j} ={j*i} ' , end='\t' ) i += 1 print () j += 1
for 循环 语法 1 2 3 4 for 临时变量 in 序列: 重复执行的代码1 重复执行的代码2 ......
1 2 3 str1 = 'itheima' for i in str1: print (i)
break 1 2 3 4 5 6 str1 = 'itheima' for i in str1: if i == 'e' : print ('遇到e不打印' ) break print (i)
continue 1 2 3 4 5 6 str1 = 'itheima' for i in str1: if i == 'e' : print ('遇到e不打印' ) continue print (i)
else while…else 引言
1 2 3 4 5 i = 1 while i <= 5 : print ('媳妇⼉儿,我错了' ) i += 1 print ('媳妇⼉儿原谅我了...' )
思考: 这个 print 是不是没有循环也能执行?
语法 1 2 3 4 while 条件: 条件成⽴立重复执行的代码 else : 循环正常结束之后要执行的代码
示例 1 2 3 4 5 6 i = 1 while i <= 5 : print ('媳妇⼉儿,我错了' ) i += 1 else : print ('媳妇原谅我了,真开心,哈哈哈哈' )
退出循环的方式
1 2 3 4 5 6 7 8 9 i = 1 while i <= 5 : if i == 3 : print ('这遍说的不真诚' ) break print ('媳妇⼉儿,我错了' ) i += 1 else : print ('媳妇原谅我了,真开心,哈哈哈哈' )
continue :
因为 continue 是退出当前⼀次循环,继续下一次循环,所以该循环在 continue 控制下是可以正常结束的,当循环结束后,则执⾏了 else 缩进的代码。
1 2 3 4 5 6 7 8 9 10 i = 1 while i <= 5 : if i == 3 : print ('这遍说的不真诚' ) i += 1 continue print ('媳妇⼉儿,我错了' ) i += 1 else : print ('媳妇原谅我了,真开⼼心,哈哈哈哈' )
for…else 语法 1 2 3 4 5 for 临时变量 in 序列: 重复执⾏的代码 ... else : 循环正常结束之后要执行的代码
所谓 else 指的是循环正常结束之后要执⾏的代码,即如果是 break 终止循环的情况,else 下方缩进的代码将不执行
示例 1 2 3 4 5 str1 = 'itheima' for i in str1: print (i) else : print ('循环正常结束之后执行的代码' )
退出循环的方式
1 2 3 4 5 6 7 8 str1 = 'itheima' for i in str1: if i == 'e' : print ('遇到e不打印' ) break print (i) else : print ('循环正常结束之后执行的代码' )
continue 控制循环 :
因为 continue 是退出当前⼀次循环,继续下⼀次循环,所以该循环在 continue 控制下是可以正常结束的,当循环结束后,则执行了 else 缩进的代码。
1 2 3 4 5 6 7 8 str1 = 'itheima' for i in str1: if i == 'e' : print ('遇到e不打印' ) continue print (i) else : print ('循环正常结束之后执行的代码' )
总结
循环的作用:控制代码重复执行
while 语法 :
1 2 3 4 while 条件: 条件成⽴重复执行的代码1 条件成⽴重复执行的代码2 ......
1 2 3 4 5 6 while 条件1 : 条件1 成⽴立执行的代码 ...... while 条件2 : 条件2 成⽴立执行的代码 ......
1 2 3 4 for 临时变量 in 序列: 重复执行的代码1 重复执行的代码2 ......
break 退出整个循环
continue 退出本次循环,继续执行下⼀次重复执行的代码
else
while 和 for 都可以配合 else 使用
else 下方缩进的代码含义:当循环正常结束后执行的代码
break 终止循环不会执行 else 下⽅缩进的代码
continue 退出循环的方式执行 else 下方缩进的代码
字符串 学习目标
认识字符串
字符串是 Python 中最常用的数据类型。我们⼀般使用引号来创建字符串。创建字符串很简单,只要为变量分配一个值即可。
注意:控制台显示结果为<class 'str'>
, 即数据类型为 str(字符串)。
1 2 3 4 a = 'hello world' b = "abcdefg" print (type (a))print (type (b))
字符串特征
1 2 name1 = 'Tom' name2 = "Rose"
1 2 3 4 5 6 7 name3 = ''' Tom ''' name4 = """ Rose """ a = ''' i am Tom, nice to meet you! ''' b = """ i am Rose, nice to meet you! """
注意:三引号形式的字符串支持换行。
思考:如果创建一个字符串 I'm Tom
?
1 2 c = "I'm Tom" d = 'I\'m Tom'
字符串输出 1 2 3 4 5 print ('hello world' )name = 'Tom' print ('我的名字是%s' % name)print (f'我的名字是{name} ' )
字符串输入
在 Python 中,使用 input()
接收用户输入。
1 2 3 4 5 6 7 name = input ('请输入您的名字:' ) print (f'您输入的名字是{name} ' )print (type (name))password = input ('请输入您的密码:' ) print (f'您输入的密码是{password} ' )print (type (password))
字符串下标
1 2 3 4 5 name = "abcdef" print (name[1 ])print (name[0 ])print (name[2 ])
切片
切片是指对操作的对象截取其中⼀部分的操作。字符串、列表、元组都⽀持切片操作。
语法
注意
不包含结束位置下标对应的数据, 正负整数均可;
步长是选取间隔,正负整数均可,默认步长为 1。
1 2 3 4 5 6 7 8 9 10 11 name = "abcdefg" print (name[2 :5 :1 ]) print (name[2 :5 ]) print (name[:5 ]) print (name[1 :]) print (name[:]) print (name[::2 ]) print (name[:-1 ]) print (name[-4 :-1 ]) print (name[::-1 ])
常用操作方法
查找
所谓字符串查找方法即是查找子串在字符串中的位置或出现的次数。
find()
1 字符串序列.find(⼦串, 开始位置下标, 结束位置下标)
1 2 3 4 5 mystr = "hello world and itcast and itheima and Python" print (mystr.find('and' )) print (mystr.find('and' , 15 , 30 )) print (mystr.find('ands' ))
rfind()
index()
1 字符串序列.index(⼦串, 开始位置下标, 结束位置下标)
1 2 3 4 5 mystr = "hello world and itcast and itheima and Python" print (mystr.index('and' )) print (mystr.index('and' , 15 , 30 )) print (mystr.index('ands' ))
rindex()
和 index() 功能相同,但查找方向为右侧开始
count()
返回某个子串在字符串中出现的次数
语法
注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。
1 字符串序列.count(⼦串, 开始位置下标, 结束位置下标)
1 2 3 4 5 mystr = "hello world and itcast and itheima and Python" print (mystr.count('and' )) print (mystr.count('ands' )) print (mystr.count('and' , 0 , 20 ))
修改
所谓修改字符串,指的就是通过函数的形式修改字符串中的数据。
replace()
1 字符串序列.replace(旧⼦串, 新⼦串, 替换次数)
注意:替换次数如果查出⼦串出现次数,则替换次数为该⼦串出现次数。
1 2 3 4 5 6 7 8 9 10 mystr = "hello world and itcast and itheima and Python" print (mystr.replace('and' , 'he' ))print (mystr.replace('and' , 'he' , 10 ))print (mystr)
注意:数据按照是否能直接修改分为可变类型和不可变类型两种。
字符串类型的数据修改的时候不能改变原有字符串,属于不能直接修改数据的类型即是不可变类型。
split()
注意:num 表示的是分割字符出现的次数,即将来返回数据个数为 num+1 个。
1 2 3 4 5 6 7 8 9 10 11 12 13 mystr = "hello world and itcast and itheima and Python" print (mystr.split('and' ))print (mystr.split('and' , 2 ))print (mystr.split(' ' ))print (mystr.split(' ' , 2 ))
注意:如果分割字符是原有字符串中的⼦串,分割后则丢失该⼦串。
join()
1 2 3 4 5 6 7 8 list1 = ['chuan' , 'zhi' , 'bo' , 'ke' ] t1 = ('aa' , 'b' , 'cc' , 'ddd' ) print ('_' .join(list1))print ('...' .join(t1))
capitalize()
1 2 3 4 mystr = "hello world and itcast and itheima and Python" print (mystr.capitalize())
注意:capitalize()函数转换后,只字符串第⼀个字符大写,其他的字符全都小写
title()
1 2 3 4 mystr = "hello world and itcast and itheima and Python" print (mystr.title())
lower()
1 2 3 4 mystr = "hello world and itcast and itheima and Python" print (mystr.lower())
upper()
1 2 3 4 mystr = "hello world and itcast and itheima and Python" print (mystr.upper())
lstrip()
rstrip()
strip()
ljust()
返回⼀个原字符串左对⻬,并使⽤指定字符(默认空格)填充至对应长度 的新字符串。
rjust()
返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度 的新字符串,语法和 ljust() 相同。
center()
返回⼀个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和 ljust() 相同。
判断
所谓判断即是判断真假,返回的结果是布尔型数据类型:True 或 False。
startswith()
检查字符串是否是以指定子串开头,是则返回 True,否则返回 False。
如果设置开始和结束位置下标,则在指定范围内检查。
语法 :
1 字符串序列.startswith(⼦串, 开始位置下标, 结束位置下标)
1 2 3 4 5 6 7 mystr = "hello world and itcast and itheima and Python " print (mystr.startswith('hello' ))print (mystr.startswith('hello' , 5 , 20 ))
endswith()
检查字符串是否是以指定⼦串结尾,是则返回 True,否则返回 False。
如果设置开始和结束位置下标,则在指定范围内检查。
语法 :
1 字符串序列.endswith(⼦串, 开始位置下标, 结束位置下标)
1 2 3 4 5 6 7 8 9 10 mystr = "hello world and itcast and itheima and Python" print (mystr.endswith('Python' ))print (mystr.endswith('python' ))print (mystr.endswith('Python' , 2 , 20 ))
isalpha()
如果字符串至少有⼀个字符并且所有字符都是字母则返回 True, 否则返回 False。
1 2 3 4 5 6 7 8 mystr1 = 'hello' mystr2 = 'hello12345' print (mystr1.isalpha())print (mystr2.isalpha())
isdigit()
如果字符串只包含数字则返回 True 否则返回 False
1 2 3 4 5 6 7 8 mystr1 = 'aaa12345' mystr2 = '12345' print (mystr1.isdigit())print (mystr2.isdigit())
isalnum()
如果字符串至少有⼀个字符并且所有字符都是字母或数字则返 回 True,否则返回 False。
1 2 3 4 5 6 7 8 mystr1 = 'aaa12345' mystr2 = '12345-' print (mystr1.isalnum())print (mystr2.isalnum())
isspace()
如果字符串中只包含空白,则返回 True,否则返回 False。
1 2 3 4 5 6 7 8 mystr1 = '1 2 3 4 5' mystr2 = ' ' print (mystr1.isspace())print (mystr2.isspace())
总结
下标
计算机为数据序列中每个元素分配的从 0 开始的编号
切⽚
列表 学习目标
列表的应⽤场景
列表的格式
列表的常用操作
列表的循环遍历
列表的嵌套使用
列表的应用场景
思考:有一个人的姓名(TOM)怎么书写存储程序?
思考:如果⼀个班级 100 位学生,每个人的姓名都要存储,应该如何书写程序?声明 100 个变量吗?
列表的格式 1 [数据1 , 数据2 , 数据3 , 数据4. .....]
列表可以一次性存储多个数据,且可以为不同数据类型。
列表的常用操作
列表的作用是一次性存储多个数据,程序员可以对这些数据进行的操作有:增、删、改、查。
查找 下标 1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] print (name_list[0 ]) print (name_list[1 ]) print (name_list[2 ])
index()
1 列表序列.index(数据, 开始位置下标, 结束位置下标)
1 2 name_list = ['Tom' , 'Lily' , 'Rose' ] print (name_list.index('Lily' , 0 , 2 ))
count()
1 2 name_list = ['Tom' , 'Lily' , 'Rose' ] print (name_list.count('Lily' ))
len()
1 2 name_list = ['Tom' , 'Lily' , 'Rose' ] print (len (name_list))
判断是否存在 in
判断指定数据在某个列表序列,如果在返回 True,否则返回 False
1 2 3 4 5 6 7 name_list = ['Tom' , 'Lily' , 'Rose' ] print ('Lily' in name_list)print ('Lilys' in name_list)
not in
判断指定数据不在某个列表序列,如果不在返回 True,否则返回 False
1 2 3 4 5 6 7 name_list = ['Tom' , 'Lily' , 'Rose' ] print ('Lily' not in name_list)print ('Lilys' not in name_list)
1 2 3 4 5 6 7 name_list = ['Tom' , 'Lily' , 'Rose' ] name = input ('请输入您要搜索的名字:' ) if name in name_list: print (f'您输入的名字是{name} , 名字已经存在' ) else : print (f'您输入的名字是{name} , 名字不存在' )
增加
append()
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.append('xiaoming' ) print (name_list)
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.append(['xiaoming' , 'xiaohong' ]) print (name_list)
extend()
列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一添加到列表。
语法
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.extend('xiaoming' ) print (name_list)
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.extend(['xiaoming' , 'xiaohong' ]) print (name_list)
insert()
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.insert(1 , 'xiaoming' ) print (name_list)
删除 del
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] del name_listprint (name_list)
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] del name_list[0 ]print (name_list)
pop()
1 2 3 4 5 6 7 8 name_list = ['Tom' , 'Lily' , 'Rose' ] del_name = name_list.pop(1 ) print (del_name)print (name_list)
remove()
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.remove('Rose' ) print (name_list)
clear()
1 2 3 4 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list.clear() print (name_list)
修改
1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_list[0 ] = 'aaa' print (name_list)
reverse()
1 2 3 4 5 num_list = [1 , 5 , 2 , 3 , 6 , 8 ] num_list.reverse() print (num_list)
sort()
1 列表序列.sort( key=None , reverse=False )
注意:reverse 表示排序规则,reverse = True
降序, reverse = False
升序(默认)
1 2 3 4 5 num_list = [1 , 5 , 2 , 3 , 6 , 8 ] num_list.sort() print (num_list)
复制 copy() 1 2 3 4 5 name_list = ['Tom' , 'Lily' , 'Rose' ] name_li2 = name_list.copy() print (name_li2)
列表的循环遍历
while 1 2 3 4 5 6 name_list = ['Tom' , 'Lily' , 'Rose' ] i = 0 while i < len (name_list): print (name_list[i]) i += 1
for 1 2 3 name_list = ['Tom' , 'Lily' , 'Rose' ] for i in name_list: print (i)
列表嵌套
所谓列表嵌套指的就是⼀个列表里⾯包含了其他的子列表。
应⽤场景:要存储班级⼀、⼆、三个班级学⽣姓名,且每个班级的学生姓名在⼀个列表。
1 name_list = [['⼩小明' , '⼩小红' , '⼩小绿' ], ['Tom' , 'Lily' , 'Rose' ], ['张三' , '李李四' ,'王五' ]]
1 2 3 4 5 print (name_list[2 ])print (name_list[2 ][1 ])
总结
常用操作方法
index()
len()
append()
pop()
remove()
列表嵌套
1 2 name_list = [['⼩小明' , '⼩小红' , '⼩小绿' ], ['Tom' , 'Lily' , 'Rose' ], ['张三' , '李李四' ,'王五' ]] name_list[2 ][1 ]
元组 学习目标
元组的应用场景
思考:如果想要存储多个数据,但是这些数据是不能修改的数据,怎么做?
答:列表?列表可以一次性存储多个数据,但是列表中的数据允许更改。
1 2 num_list = [10 , 20 , 30 ] num_list[0 ] = 100
定义元组
元组特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型。
一个元组可以存储多个数据,元组内的数据是不能修改的。
1 2 3 4 5 t1 = (10 , 20 , 30 ) t2 = (10 ,)
注意:如果定义的元组只有一个数据,那么这个数据后⾯面也好添加逗号,否则数据类型为唯一的这个数据的数据类型
1 2 3 4 5 6 7 8 t2 = (10 ,) print (type (t2)) t3 = (20 ) print (type (t3)) t4 = ('hello' ) print (type (t4))
元组的常见操作
按下标查找数据 1 2 tuple1 = ('aa' , 'bb' , 'cc' , 'bb' ) print (tuple1[0 ])
index()
查找某个数据,如果数据存在返回对应的下标,否则报错,语法和列表、字符串的 index 方法相同。
1 2 tuple1 = ('aa' , 'bb' , 'cc' , 'bb' ) print (tuple1.index('aa' ))
count()
1 2 tuple1 = ('aa' , 'bb' , 'cc' , 'bb' ) print (tuple1.count('bb' ))
len()
1 2 tuple1 = ('aa' , 'bb' , 'cc' , 'bb' ) print (len (tuple1))
1 2 tuple1 = ('aa' , 'bb' , 'cc' , 'bb' ) tuple1[0 ] = 'aaa'
但是如果元组里面有列表,修改列表⾥面的数据则是支持的,故自觉很重要。
1 2 3 4 5 6 tuple2 = (10 , 20 , ['aa' , 'bb' , 'cc' ], 50 , 30 ) print (tuple2[2 ]) tuple2[2 ][0 ] = 'aaaaa' print (tuple2)
总结 定义元组 1 2 t1 = (10 , 20 , 30 ) t2 = (10 ,)
常用操作方法
字典 学习目标
字典的应用场景
创建字典的语法
字典常见操作
字典的循环遍历
应用场景
思考1: 如果有多个数据,例如:’Tom’, ‘男’, 20,如何快速存储?
1 list1 = ['Tom' , '男' , 20 ]
思考3:如果将来数据顺序发生变化,如下所示,还能用 list1[0] 访问到数据’Tom’吗?。
1 list1 = ['男' , 20 , 'Tom' ]
- 思考4:数据顺序发生变化,每个数据的下标也会随之变化,如何保证数据顺序变化前后能使用同一的标准查找数据呢?
答:字典,字典里面的数据是以键值对形式出现,字典数据和数据顺序没有关系,即字典不支持下标,后期无论数据如何变化,只需要按照对应的键的名字查找数据即可。
创建字典语法
字典特点:
符号为大括号
数据为键值对形式出现
各个键值对之间用逗号隔开
1 2 3 4 5 6 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } dict2 = {} dict3 = dict ()
注意:一般称冒号前面的为键(key),简称k;冒号后面的为值(value),简称v。
字典常见操作 增加
写法:字典序列[key] = 值
注意:如果key存在则修改这个key对应的值;如果key不存在则新增此键值对
注意:字典为可变类型
1 2 3 4 5 6 7 8 9 10 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } dict1['name' ] = 'Rose' print (dict1)dict1['id' ] = 110 print (dict1)
删除
del()
/ del
:删除字典或删除字典中指定键值对
1 2 3 4 5 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } del dict1['gender' ]print (dict1)
1 2 3 4 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } dict1.clear() print (dict1)
修改
写法:字典序列[key] = 值
注意:如果 key 存在则修改这个key对应的值 ;如果key不存在则新增此键值对。
查找 key值查找 1 2 3 4 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } print (dict1['name' ]) print (dict1['id' ])
如果当前查找的key存在,则返回对应的值;否则报错
get()
语法
注意:如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回 None。
1 2 3 4 5 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } print (dict1.get('name' )) print (dict1.get('id' , 110 )) print (dict1.get('id' ))
keys() 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } print (dict1.keys())
values() 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } print (dict1.values())
items() 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } print (dict1.items())
字典的循环遍历 遍历字典的key 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } for key in dict1.keys(): print (key)
遍历字典的value 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } for value in dict1.values(): print (value)
遍历字典的元素 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } for item in dict1.items(): print (item)
遍历字典的键值对 1 2 3 dict1 = {'name' : 'Tom' , 'age' : 20 , 'gender' : '男' } for key, value in dict1.items(): print (f'{key} = {value} ' )
总结
1 2 3 dict1 = {'name' : 'Python' , 'age' : 30 } dict2 = {} dict3 = dict ()
查找
字典序列[key]
keys()
values()
items()
集合 学习目标
创建集合
创建集合使用 {}
或 set()
,但是如果要创建空集合只能使用 set()
,因为 {}
用来创建空字典。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 s1 = {10 , 20 , 30 , 40 , 50 } print (s1)s2 = {10 , 30 , 20 , 10 , 30 , 40 , 30 , 50 } print (s2)s3 = set ('abcdefg' ) print (s3)s4 = set () print (type (s4)) s5 = {} print (type (s5))
特点:
集合可以去掉重复数据;
集合数据是无序的,故不支持下标
集合常见操作方法 增加数据 add()
因为集合有去重功能,所以,当向集合内追加的数据是当前集合已有数据的话,则不进行任何操作。
1 2 3 4 5 s1 = {10 , 20 } s1.add(100 ) s1.add(10 ) print (s1)
update()
1 2 3 4 5 6 s1 = {10 , 20 } s1.update([100 , 200 ]) s1.update('abc' ) print (s1)
删除数据 remove()
1 2 3 4 5 6 7 s1 = {10 , 20 } s1.remove(10 ) print (s1)s1.remove(10 ) print (s1)
discard()
1 2 3 4 5 6 7 s1 = {10 , 20 } s1.discard(10 ) print (s1)s1.discard(10 ) print (s1)
pop()
1 2 3 4 5 s1 = {10 , 20 , 30 , 40 , 50 } del_num = s1.pop() print (del_num)print (s1)
查找数据
in
:判断数据在集合序列
not in
:判断数据不在集合序列
1 2 3 4 s1 = {10 , 20 , 30 , 40 , 50 } print (10 in s1)print (10 not in s1)
总结
公共操作 学习目标
运算符
运算符
描述
支持的容器类型
+
合并
字符串、列表、元组
*
复制
字符串、列表、元组
in
元素是否存在
字符串、列表、元组、字典
not in
元素是否不存在
字符串、列表、元组、字典
+ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 str1 = 'aa' str2 = 'bb' str3 = str1 + str2 print (str3) list1 = [1 , 2 ] list2 = [10 , 20 ] list3 = list1 + list2 print (list3) t1 = (1 , 2 ) t2 = (10 , 20 ) t3 = t1 + t2 print (t3)
* 1 2 3 4 5 6 7 8 9 10 print ('-' * 10 ) list1 = ['hello' ] print (list1 * 4 ) t1 = ('world' ,) print (t1 * 4 )
in或not in 1 2 3 4 5 6 7 8 9 10 11 12 13 print ('a' in 'abcd' ) print ('a' not in 'abcd' ) list1 = ['a' , 'b' , 'c' , 'd' ] print ('a' in list1) print ('a' not in list1) t1 = ('a' , 'b' , 'c' , 'd' ) print ('aa' in t1) print ('aa' not in t1)
公共方法
函数
描述
len()
计算容器器中元素个数
del 或 del()
删除
max()
返回容器中元素最大值
min()
返回容器中元素最小值
range(start,end, step)
生成从start到end的数字,步长为 step,供for循环使用
enumerate()
函数⽤于将一个可遍历的数据对象(如列表、元组或字符串)组合为⼀个索引序列,同时列出数据和数据下标,⼀般用在 for 循环当中。
len() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 str1 = 'abcdefg' print (len (str1)) list1 = [10 , 20 , 30 , 40 ] print (len (list1)) t1 = (10 , 20 , 30 , 40 , 50 ) print (len (t1)) s1 = {10 , 20 , 30 } print (len (s1)) dict1 = {'name' : 'Rose' , 'age' : 18 } print (len (dict1))
del() 1 2 3 4 5 6 7 8 9 str1 = 'abcdefg' del str1print (str1)list1 = [10 , 20 , 30 , 40 ] del (list1[0 ])print (list1)
max() 1 2 3 4 5 6 7 str1 = 'abcdefg' print (max (str1)) list1 = [10 , 20 , 30 , 40 ] print (max (list1))
min() 1 2 3 4 5 6 7 str1 = 'abcdefg' print (min (str1)) list1 = [10 , 20 , 30 , 40 ] print (min (list1))
range()
1 2 3 4 5 6 7 8 9 10 11 for i in range (1 , 10 , 1 ): print (i) for i in range (1 , 10 , 2 ): print (i) for i in range (10 ): print (i)
enumerate()
语法
注意:start参数用来设置遍历数据的下标的起始值,默认为0。
1 enumerate (可遍历对象, start=0 )
1 2 3 4 5 6 7 list1 = ['a' , 'b' , 'c' , 'd' , 'e' ] for i in enumerate (list1): print (i) for index, char in enumerate (list1, start=1 ): print (f'下标是{index} , 对应的字符是{char} ' )
容器类型转换 tuple()
1 2 3 4 5 list1 = [10 , 20 , 30 , 40 , 50 , 20 ] s1 = {100 , 200 , 300 , 400 , 500 } print (tuple (list1))print (tuple (s1))
list()
1 2 3 4 5 t1 = ('a' , 'b' , 'c' , 'd' , 'e' ) s1 = {100 , 200 , 300 , 400 , 500 } print (list (t1))print (list (s1))
set()
1 2 3 4 5 list1 = [10 , 20 , 30 , 40 , 50 , 20 ] t1 = ('a' , 'b' , 'c' , 'd' , 'e' ) print (set (list1))print (set (t1))
总结
运算符
公共方法
len()
del()
range()
enumerate()
数据类型转换
推导式 学习目标
列表推导式
作用:⽤一个表达式创建⼀个有规律的列表或控制一个有规律列表。
列表推导式又叫列表生式。
快速体验
需求:创建一个 0-10 的列表
while循环实现
1 2 3 4 5 6 7 8 9 10 list1 = [] i = 0 while i < 10 : list1.append(i) i += 1 print (list1)
1 2 3 4 5 list1 = [] for i in range (10 ): list1.append(i) print (list1)
1 2 list1 = [i for i in range (10 )] print (list1)
带if的列表推导式
需求:创建 0-10 的偶数列表
方法一:range() 步长实现
1 2 list1 = [i for i in range (0 , 10 , 2 )] print (list1)
1 2 list1 = [i for i in range (10 ) if i % 2 == 0 ] print (list1)
多个for循环实现列表推导式
1 [(1 , 0 ), (1 , 1 ), (1 , 2 ), (2 , 0 ), (2 , 1 ), (2 , 2 )]
1 2 list1 = [(i, j) for i in range (1 , 3 ) for j in range (3 )] print (list1)
字典推导式
1 2 list1 = ['name' , 'age' , 'gender' ] list2 = ['Tom' , 20 , 'man' ]
如何快速合并为一个字典?
字典推导式作用:快速合并列表为字典或提取字典中目标数据。
快速体验
创建一个字典:字典 key 是 1-5 数字,value 是这个数字的 2 次方。
1 2 dict1 = {i: i**2 for i in range (1 , 5 )} print (dict1)
1 2 3 4 5 list1 = ['name' , 'age' , 'gender' ] list2 = ['Tom' , 20 , 'man' ] dict1 = {list1[i]: list2[i] for i in range (len (list1))} print (dict1)
1 2 3 4 5 counts = {'MBP' : 268 , 'HP' : 125 , 'DELL' : 201 , 'Lenovo' : 199 , 'acer' : 99 } count1 = {key: value for key, value in counts.items() if value >= 200 } print (count1)
集合推导式
1 2 3 list1 = [1 , 1 , 2 ] set1 = {i ** 2 for i in list1} print (set1)
总结
1 2 3 4 5 6 7 8 [xx for xx in range ()] {xx1: xx2 for ... in ...} {xx for xx in ...}