- python用途&特点
- python基础语法
- 缩进
- 注释
- 变量
- 创建变量
- 命名变量的规则
- 多字变量名(含有多个单词)
- 强制转换
- 获取数据类型(使用type()函数)
- 字符串类型变量
- 输出变量
- 用户输入
- 全局变量(在函数外部创建的变量)
- 全局关键字global
- 数据类型
- 内置数据类型
- 设定数据类型
- 随机数
- 字符串是数组
- 字符串切片
- 修改字符串
- 字符串格式化
- 转义字符
- 内置bool()函数
- 内置isinstance()函数
- 操作符
- 算数运算符
- 赋值运算符
- 比较运算符
- 逻辑运算符
- 身份运算符
- 成员运算符
- 按位运算符
- 列表List
- 列表项
- 列表长度
- 访问列表项
- 索引范围(与字符串切片类似)
- 检查项目是否存在
- 更改项目值
- 更改范围内的项目值
- 追加项目
- 扩展列表
- 删除指定项目
- 删除指定索引的项目
- 清空列表
- 遍历列表
- List Comprehension
- 排序列表
- 复制列表
- 连接两个列表
- 元组Tuple
- 项目元组的访问、索引范围、检查项目是否存在
- 更改元组值
- 添加、删除元组值
- 解包元组
- 遍历元组
- 元组连接
- 元组乘法
- 集合Set
- 访问项目
- 添加集合
- 删除项目
- 清空集合
- 连接集合
- 字典Dictionary
- 字典长度
- 访问项目
- 获取键(key)
- 获取值(value)
- 获取项目
- 检查key是否存在
- 更改字典项目
- 更新字典
- 添加字典项目
- 删除字典项
- 循环字典
- 复制字典
- 嵌套字典
- 语句
- 条件语句
- 循环语句
- break语句
- continue语句
- 循环后的else
- range()函数
- Try Except
- 异常处理
- 引发异常
- 函数
- 创建函数
- 参数数量
- 任意参数*args
- 关键字参数
- 任意关键字参数**kwargs
- 默认参数值
- 返回值
- pass语句
- 递归
- Lambda函数
- 语法
- 类&对象
- 类的创建
- 对象的创建
- init()函数
- 对象方法
- self参数
- 修改对象属性
- 删除对象属性
- 删除对象
- 继承
- 父类
- 子类
- 子类中增加属性
- 子类中增加方法
- python迭代器
- 停止迭代
- 模块
- 使用模块
- 从模块中导入部分内容
- 文件处理
- 文件读取
- 关闭文件
- 写入现有文件
- 创建新文件
- 删除文件
- 检查文件是否存在
1.可以做web程序、工作流、数据库系统、读取修改文件、处理大数据和执行复杂的数学运算、快速原型设计、软件开发
2.python可以在解释器系统上运行,不需要编译
3.可以通过过程方式、面向对象、函数方式处理python
python可以通过有无缩进判断是原代码块还是下一代码块。缩进的空格数可以自行决定,但同一代码块中缩进的空格数相同。
注释1.可用来解释代码和阻止测试代码执行
2.以#开头,python会忽略该行中#之后的部分
3.用前后三个单引号或双引号包裹的,没有赋给变量的,多行字符串当作多行注释
#hello """ Hello! I am sanjiang. How are you? """变量 创建变量
1.python变量无需声明,赋值时会创建变量,赋值之后可以改成该类型或者其他类型的数据
x = 5 x = 10 x = "hello"
2.可以在一行中为多个变量赋值
x,y,z = "a","b","c"
3.多个变量赋值相同
x,y,z = "a"
4.拆包(可以将列表、元组中的值按顺序提取到变量中)
color = ["red","green","blue"] x,y,z = color #x、y、z对应的值为red、green、blue命名变量的规则
- 变量名可以简短或者带有描述性
- 变量名必须以字母或者下划线开头,不能以数字开头
- 变量名只能包含数字、字母以及下划线
- 变量名区分大小写(egg、Egg、EGG是不同的变量)
1.骆驼形式(除了第一个单词,其他单词均已大写字母开头)
myName = "sanjiang"
2.帕斯卡形式(每个单词均以大写字母开头)
MyName = "sanjiang"
3.蛇形式(每两个单词之间用下划线隔开)
my_name = "sanjiang"强制转换
语法:变量名 = 转换后的数据类型(变量存储的数据)
x = str(5)获取数据类型(使用type()函数)
语法:type(变量名)
x = "hello" type(x)字符串类型变量
既可以用单引号也可以用双引号把字符串括起来。
x = 'hello' x = "hello" #多行字符串 x = '''hello! world''' x = """hello! world"""输出变量
打印语句用于输出变量,+字符有连接作用,可以连接相同类型变量,对于数字,+是加法运算符。不同类型的变量不能用+连接,文本不能和数字相连。
y = "python is" z = "awesome" print(y+z)#连接两个文本变量,输出python is awesome a = 2 b = 3 print(a+b)#加法运算,输出5用户输入
python3.6使用input()方法
python2.7使用raw_input()方法
user1 = input("please input your username:")
print("username is "+user1)
user2 = raw_input("please input your user name:")
print("username is "+user2)
全局变量(在函数外部创建的变量)
x = "hello "#全局变量 def myfunc() x = "你好 "#局部变量 print(x+"世界") print(x+"world") myfunc() #输出 你好 世界 #输出 hello world全局关键字global
可以修饰函数内的局部变量,使其变成全局变量。也可以在函数外创建全局变量之后,在函数内部先使用global修饰变量,再修改变量值。
x = "hello " def myfunc() global x = "你好" print(x+"世界") myfunc() #输出 你好 世界数据类型 内置数据类型
- 文本:str
- 数字:int(整型,长度不限的正负数)、float(含一位或多位小数的正负数,也可以时带有e或E的科学数字)、complex(复数,含有j作为虚部)
- 序列:list、tuple、range
- 映射:dict
- 集合:set、frozenset
- 布尔:bool
- 二进制:bytes、bytearray、memoryview
可以在创建对象时完成,可以直接以该类型数据的形式赋值,也可以使用该类型的构造函数。
x = set(("apple","banana","cherry"))
y = {'apple', 'banana', 'cherry'}
print(x)
print(y)
#都输出{'cherry', 'banana', 'apple'}
随机数
python没有random()函数,但是有random的内置模块。
import random print(random.randrange(1,10))#输出以一个1-10的随机数字符串是数组
1.python没有字符数据类型,单个字符是一个长度为一的字符串。python中的字符串是表示unicode字符是字节数组
x = "hello,world" print(x[0])#输出 h print(x[1])#输出 e
2.还可以用for循环遍历字符串中的字符
for x in "hello" print(x)#依次输出 h e l l o
3.获取字符串长度(使用len()函数)
print(len("hello,world"))
#输出 11
4.检查字符串中是否存在字符或字符串
使用成员运算符in,含有则为True;not in,不含有则为True
txt = "Python is awesome!"
print("is" in txt)#输出 True
print("Java" not in txt)#输出True
print("a" in txt)#输出True
字符串切片
切片语法:变量名[开始索引:结束索引]
从头[0]开始可以省略开始索引,取到最后可以省略结束索引,从开始索引取到结束索引前一位。
x = "hello" print(x[1:3])#输出 el print(x[:3])#输出 hel print(x[1:])#输出 ello
负索引从字符串的末尾[-1]开始,从右往左数,从开始索引取到结束索引前一位。
x = "hello" print(x[-3:-1])#输出 ll修改字符串
1.字符串转换成大写:变量名.upper()
2.字符串转换成小写:变量名.lower()
3.删除前后空格:变量名.strip()
4.替换:变量名.replace(被替换的部分(字符或字符串),替换之后的部分(字符或字符串))
5.拆分split(起分隔作用的字符或字符串)
x = "hi"
print(x.upper())#输出 HI
X = "HI"
print(X.lower())#输出 hi
y = "hello"
print(y.replace("llo","art"))#输出 heart
z = " hello,world "
print(z.strip())#输出 hello,world
p = "hello,world"
print(p.split(",w))#输出 ['hello', 'orld']
字符串格式化
python中使用format()方法组合字符串和数字。format()方法接受无限数量的参数,并把它们格式化,然后按顺序或者变量名放置在各自的占位符中。
age = 18
txt = "She is {}."
print(txt.format(age))#输出 She is 18.
a = 1
b = 2
c = 3
num = "{1}+{2}={0}"
print(num.format(c,b,a))#从左往右,从0开始数,对应b+a=c
#输出 2+1=3
sen = "I love {dish} most."
print(sen.format(dish = "tofu"))
#输出 I love tofu best.
转义字符
要在字符串中插入非法字符,需要在字符前加
txt = "We are "family"." print(txt)#输出 We are family.内置bool()函数
bool()函数里是0、空字符串、[]、{}、“”、None,就会返回False,其他情况多为True
print(bool(0))
print(bool(""))
print(bool(None))
print(bool([]))
print(bool({}))
#输出都是 False
内置isinstance()函数
用于判断某种数据类型
x = 10 print(x,float)#输出 False操作符 算数运算符
print(1+2)#加 输出3 print(4-2)#减 输出2 print(2*3)#乘 输出6 print(8/4)#除 输出2.0 print(5%3)#取余 输出2 print(3**2)#3的2次方 输出9 print(7//2)#整除 输出3赋值运算符
为变量赋值
= 最基本的赋值运算 x = y += 加赋值 x += y x = x + y -= 减赋值 x -= y x = x - y *= 乘赋值 x *= y x = x * y /= 除赋值 x /= y x = x / y %= 取余数赋值 x %= y x = x % y **= 幂赋值 x **= y x = x ** y //= 取整数赋值 x //= y x = x // y &= 按位与赋值 x &= y x = x & y |= 按位或赋值 x |= y x = x | y ^= 按位异或赋值 x ^= y x = x ^ y <<= 左移赋值 x <<= y x = x << y,这里的 y 指的是左移的位数 >>= 右移赋值 x >>= y x = x >> y,这里的 y 指的是右移的位数比较运算符
用于比较两个值
print(1==2)#相等 输出False print(1!=2)#不相等 输出True print(1>2)#大于 输出False print(1>=2)#大于等于 输出False print(1<2)#小于 输出True print(1<=2)#小于等于 输出Flase逻辑运算符
用于组合条件语句
print(1<2 and 2<3)#与 两个为True才是True print(1<2 or 2>3)#或 有True就是True print(not(3>5))#非 True为False,False为True身份运算符
用于判断两个变量是否指向同一个对象,内存地址相同
x = y = "hhh" print(x is y)#输出 True print(x is not y)#输出 False a = "hhh" b = "hhh" print(a is b)#输出 False成员运算符
用于测试序列中是否存在于对象中
x = 1 y = [1,2,3] print(x in y)#输出 True print(x not in y)#输出 False按位运算符
用于比较二进制数字
a = 4 b = 10 ''' 二进制 a = 0000 0100 1234 b = 0000 1010 ''' print(a&b) ''' 与:a、b二进制的每一位进行与(两数都为1才是1,其他情况都是0)运算:前四位都取0,1位取0,2位取0,3位取0,4位取0 a&b二进制为0000 0000;输出 0 ''' print(a|b) ''' 或:a、b二进制的每一位进行或(两数都为0才是0,其他情况都是1)运算:前4位都取0,1位取1,2位取1,3位取1,4位取0 a&b二进制为0000 1110;输出 14 ''' print(~a) ''' 非:a的每一位取非(0变1,1变0):前四位都取1,1位取1,2位取0,3位取1,4位取1 ~a二进制为1111 1011;输出-11 ''' print(a^b) ''' 异或:a、b二进制的每一位进行异或(相同取0,不相同取1)运算:前四位都取0,相同为0,不相同为1:1位取1,2位取1,3位取1,4位取0 a^b二进制为0000 1110;输出14 '''
a = 5#a = 0000 0101 print(a>>2) ''' 右移2位:删去最后2位,在前面添2个0,二进制为0000 0001;输出1 ''' print(a<<1) ''' 左移1位:删去后四位的前1位,在最后填1个0,二进制位0000 1010;输出10 '''列表List
用于在单个变量中存储多个项目(同种或混合数据类型都可以)。列表是python存储数据集合的4种内置数据类型之一,其他三种是元组Tuple、集合Set和字典Dictionary。
thelist = ['a','b','c']#直接创建
thelist = list('a','b','c')#list()构造函数创建
列表项
列表项是有序、可变的,允许重复
1.有序
列表项已经编入索引,第一个项是[0],以此类推,添加新的项目会放置在列表的末尾
3.可变
可以在创建列表后更改、添加、删除
4.允许重复
重复的项对应索引不同
len()函数获取列表的长度,即列表项的数量。
list = ['a','b','c'] print(list.len())#输出 3访问列表项
可以通过正索引(从头[0]开始数)或负索引(从尾[-1]开始数)
list = ['a','b','c'] print(list[1])#输出 b print(list[-3])#输出 a索引范围(与字符串切片类似)
list = ['a','b','c','d'] print(list[:3])#输出 ['a','b','c'] 从头开始可以省略开始索引 print(list[1:])#输出 ['b','c','d'] 取到结尾可以省略结束索引 print(list[1:3])#输出 ['b','c']不包括list[3] print(list[-4:-2])#输出 ['c','b']不包括list[-4]检查项目是否存在
使用in关键字
list = ['a','b','c']
print('a' in list)#输出 True
print('a' not inlist)#输出 False
更改项目值
指定索引项目进行更改
list = ['a','b','c'] print(list[2])#输出 c list[2] = 'd' print(list[2])#输出 d更改范围内的项目值
指定原有列表索引范围后,赋上新的列表,将其替换原列表中对应的范围
list = ['a','b','c'] #新列表项目数量大于指定范围 list[1:2] = ['A','B'] print(list)#输出 ['a', 'A', 'B', 'c'] 相当于把[list[1]](['b'])替换成['A', 'B'] #新列表项目数量小于指定范围 list = ['a','b','c] list[0:2] = ['A'] print(list)#输出 ['A', 'c'] 相当于把[list[0],list[1]]替换成['A']追加项目
使用append()函数可以将项目添加至列表末尾
list = ['a','b','c']
list.append('d')#只能追加一个项目
print(list)#输出 ['a','b','c','d']
扩展列表
使用extend()函数将另一列表的项目添加至当前列表
list1 = ['a','b','c'] list2 = ['e','f'] list1.extend(list2) print(list1)#输出 ['a', 'b', 'c', 'e', 'f']删除指定项目
使用remove()函数
list = ['a', 'b', 'c', 'e', 'f']
list.remove('e')#只能删除一个项目
print(list)#输出 ['a', 'b', 'c', 'f']
删除指定索引的项目
1.使用pop()函数,不指定索引就会删去最后一项
list = ['a', 'b', 'c', 'f'] list.pop(1) print(list)#输出 ['a', 'c', 'f'] list.pop() print(list)#输出 ['a', 'c']
2.使用del关键字
list = ['a', 'b', 'c', 'f'] del list[1] print(list)#输出 ['a', 'c', 'f']清空列表
1.使用clear()函数
list = ['a', 'b', 'c', 'e', 'f'] list.clear() print(list)#输出[]清空了项目,列表仍然存在
2.使用del关键字
list = ['a', 'b', 'c', 'e', 'f'] del list print(list)#报错 该列表不存在遍历列表
1.使用for循环
list = ['a', 'b', 'c', 'e', 'f'] for x in list: print(x) '''输出 a b c e f '''
2.通过索引遍历
len()函数获取列表长度
rang()函数获取索引范围
list = ['a', 'b', 'c', 'd', 'e'] count = range(len(list)) print(count)#输出 range(0,5) for i in count: print(list[i]) '''输出 a b c d e '''
3.使用while循环
len()函数获取列表长度,然后从0开始遍历
list = ['a', 'b', 'c', 'd', 'e'] i = 0 while i < len(list): print(list[i]) i += 1 '''输出 a b c d e '''List Comprehension
从当前列表中筛选符合条件的项目组合成新的列表,可以通过含有测试条件的循环语句。
list = ["cow","cat","bird","dog"] newList = [] for x in list: if 'c' in x:#筛选出含有c的字符串 newList.append(x) print(newList)#输出 ['cow', 'cat']
List Comprehension语法:
newList = [代表每个项目的变量x for x in 当前列表 if 筛选条件]
list = ["cow","cat","bird","dog"] newList = [x for x in list if 'c' in x] print(newList)#输出 ['cow', 'cat']排序列表
列表对象默认有一个sort()方法,可以将项目按字母或数字顺序进行升序排序。
sort(reverse = True)降序排序
list = ['e','a','c','b','d','f'] list.sort() print(list)#输出 ['a', 'b', 'c', 'd', 'e', 'f'] list = [3,2,4,1,5] list.sort() print(list)#输出 [1, 2, 3, 4, 5] #sort()方法区分大小写,所有大写字母均排在小写字母之前 list = ['E','a','c','B','d','f'] list.sort() print(list)#输出 ['B', 'E', 'a', 'c', 'd', 'f'] #降序排序 list = ['e','a','c','b','d','f'] list.sort(reverse = True) print(list)#输出 ['f', 'e', 'd', 'c', 'b', 'a']复制列表
1.使用List的copy()函数
list1 = ['a', 'b', 'c', 'd', 'e', 'f'] list2 = list1.copy() print(list2)#输出 ['a', 'b', 'c', 'd', 'e', 'f']
2.使用list()函数
list1 = ['a', 'b', 'c', 'd', 'e', 'f'] list2 = list(list1) print(list2)#输出 ['a', 'b', 'c', 'd', 'e', 'f']连接两个列表
1.使用+运算符连接
list1 = [1,2,3] list2 = [4,5] newList = list2 + list2 print(newList)#输出 [1,2,3,4,5]
2.使用append()函数逐个增加
list1 = [1,2,3] list2 = [4,5] for x in list2: list1.append(x) print(list1)#输出 [1,2,3,4,5]
3.使用extend()函数对其中一个列表进行扩展
list1 = [1,2,3] list2 = [4,5] list1.extend(list2) print(list1)#输出 [1,2,3,4,5]元组Tuple
元组是有序且不可更改的集合,用于在单个变量中存储多个项目,项目类型可以不同,是用圆括号写的。(而列表是可以更改的,项目类型必须相同,用中括号写)
x = (1,"two",'a')#可以直接创建元组 y = tuple((1,"two",'a'))#可以通过构造函数创建 注意是双括号项目元组的访问、索引范围、检查项目是否存在
均与列表相同
更改元组值元组创建后是不可更改的,但是可以将元组转换为列表,更改之后再转回元组。
使用list()函数转换成列表,tuple()函数转换成元组。
x = ('a','b','c')
y = list(x)
y[1] = 'd'
x = tuple(y)
print(x)#输出 ('a','d','c')
添加、删除元组值
先转换成列表再添加、删除,再转回元组。
解包元组创建元组时,为其分配值称为“打包”,将值提取到变量中成为“解包”。
x = ('a','b','c')
#变量数量与元组值数量相等
(x1,x2,x3) = x
print(x1)#输出 a
print(x2)#输出 b
print(x3)#输出 c
#变量数量少于元组值数量,用*修饰最后一个变量,该变量存储的是余下元组值构成的列表
(x1,*x2) = x
print(x1)#输出 a
print(x2)#输出 ['b','c']
#变量数量少于元组值数量,用*修饰的不是最后一个变量,该变量存储的是,删去已经提取到其他变量中的元组值后,剩下的元组值(是连续的)构成的列表
x = (1,2,3,4,5,6)
(x1,*x2,x3) = x
print(x1)#输出 1
print(x2)#输出 [2,3,4,5]
print(x3)#输出 6
遍历元组
与列表相同
元组连接使用+字符
元组乘法x = ('a','b','c')
y = x*3
print(y)#输出 ('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
集合Set
集合是无序、无索引(不能进行索引相关操作)不可更改(但是可以添加新项目)的集合,项目类型可以不同,用于在单个变量中存储多个数据。不允许取重复值(创建时含有重复的项目,打印出来该项目只出现一次),用大括号写。
set1 = {1,2,3,4,5}#直接创建
set2 = set((1,2,3,4,5))#使用构造函数创建 注意是双括号
访问项目
无索引,可以通过for循环遍历集合项,也通过循环使用关键字in检查特定项目是否存在于集合中。
####添加项目
使用add()函数将一个项目添加至集合中。
set1 = {1,2,3,4}
set1.add(5)
print(set1)#输出 {1,2,3,4,5}
添加集合
使用update()函数,将另一个集合添加当前集合。
set1 = {1,2,3,4}
set2 = {5}
set1.update(set2)
print(set1)#输出 {1,2,3,4,5}
update()函数中的参数可以是任何迭代对象(集合、元组、列表、字典等)函数会把参数中的值添加到当前集合。
删除项目1.可以使用remove()函数和discard()函数;如果删除的项目不存在,remove()函数会引发错误,discard()函数不会。
set1 = {1,2,3,4,5}
set1.remove(5)
print(set1)#输出 {1, 2, 3, 4}
set1 = {1,2,3,4,5}
set1.discard(6)
print(set1)#输出 {1, 2, 3, 4, 5}
2.可以使用pop()函数随机删除一个项目,在IDE中会删除左边第一个元素。
set1 = {1,2,3,4,5}
print(set1.pop())#输出 1(返回删除的项)
print(set1)#输出 {2, 3, 4, 5}(pycharm运行结果)
清空集合
使用clear()函数(清空后集合依然存在)或者del关键字(清空后该集合不存在)
连接集合1.使用union()函数返回包含两个集合的新集合。
set1 = {1,2,3}
set2 = {4,5}
set3 = set1.union(set2)
print(set3)#输出 {1,2,3,4,5}
2.使用update()函数将另一个集合的所有项添加至当前集合。
set1 = {1,2,3}
set2 = {4,5}
set1.update(set2)
print(set1)#输出 {1,2,3,4,5}
字典Dictionary
字典用于在键值对中存储数据值(可以是不同数据类型)。从python3.7开始,字典是有序的,字典可变且不允许重复(不能有两个相同键的项目),用大括号写,有键和值(用:分隔)。
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
print(dict)#输出 {'apple': 'red', 'banana': 6, 'orange': 3}
#新的"apple"键对应的"red"会替换原来的"apple"键对应的4
字典长度
使用len()函数获取字典的项目数
访问项目1.可以通过 集合名[键名] 访问项目,键名功能类似于索引
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
print(dict["apple"])#输出 red
2.通过内置函数get()访问:集合名.get(键名)函数
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
print(dict.get("apple"))#输出 red
获取键(key)
使用内置函数keys()获取字典中所有键的列表
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
print(dict.keys())#输出 dict_keys(['apple', 'banana', 'orange'])
获取值(value)
使用内置函数values()获取字典中所有值的列表
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
print(dict.values())#输出 dict_values(['red', 6, 3])
获取项目
使用内置函数items()获取字典中的每个项目,键和值构成元组,返回所有键值对元组所构成的列表:
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
print(dict.items())#输出 dict_items([('apple', 'red'), ('banana', 6), ('orange', 3)])
检查key是否存在
使用关键字in:
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
if "apple" in dict:#in之后是字典名 而不是key列表(字典名.keys())
print("yes")
更改字典项目
通过引用键名更改对应的值:
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict["apple"] = "green"
print(dict)#输出 {'apple': 'green', 'banana': 6, 'orange': 3}
更新字典
使用内置函数update(参数),参数必须是字典或者含有键值对的可迭代对象:
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict2 = {"peach":5,"orange":5}
dict1.update(dict2)
print(dict1)#输出 {'apple': 'red', 'banana': 6, 'orange': 5, 'peach': 5}
添加字典项目
1.使用新的键名,并为其分配值:
dict = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict["peach"] = 5
print(dict)#输出 {'apple': 'red', 'banana': 6, 'orange': 3, 'peach': 5}
2.update(参数)参数中为当前字典不存在的项目,就会添加该项目
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict1.update({"peach":5})
print(dict1)#输出 {'apple': 'red', 'banana': 6, 'orange': 3, 'peach': 5}
删除字典项
1.使用pop()函数,参数为指定的键名
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict1.pop("apple")
print(dict1)#输出 {'banana': 6, 'orange': 3 }
2.使用popitem()函数删除最后一个项目
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict1.popitem()
print(dict1)#输出 {'apple': 'red', 'banana': 6}
3.使用del关键字,删除指定键名对应的项目
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
del dict1["orange"]
print(dict1)#输出 {'apple': 'red', 'banana': 6}
4.使用clear()函数,清除所有项目
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict1.clear()
print(dict1)#输出 {}
循环字典
1.返回值是字典的键名
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
for x in dict1:
print(x)
'''
输出
apple
banana
orange
'''
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
for x in dict1.keys():
print(x)
'''
输出
apple
banana
orange
'''
2.返回字典的值
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
for x in dict1.values():
print(x)
'''
输出
red
6
3
'''
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
for x in dict1:
print(dict1[x])
'''
输出
red
6
3
'''
3.返回字典的键值对
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
for x,y in dict1.items():
print(x,y)
'''
输出
apple red
banana 6
orange 3
'''
复制字典
1.使用内置的Dictionary函数copy()
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict2 = dict1.copy()
print(dict2)#输出 {'apple': 'red', 'banana': 6, 'orange': 3}
2.使用构造函数dict()
dict1 = {
"apple":4,
"banana":6,
"orange":3,
"apple":"red"
}
dict2 = dict(dict1)
print(dict2)#输出 {'apple': 'red', 'banana': 6, 'orange': 3}
嵌套字典
字典中的值为字典,成为嵌套字典
shoppingList = {
"item1":{
"name":"milk"
"price":12
}
"item2":{
"name":"brush"
"price":10
}
}
语句
语句之间可以相互嵌套
条件语句常见的逻辑条件:等于、不等于、小于、小于或等于、大于、大于或等于。如果只有一个语句执行,可以和逻辑条件放在同一行。
1.if
逻辑条件成立,就执行if代码块里的语句
if 1<2:
print("yes")
#输出 yes
2.elif
前面的条件不成立,就会使用elif的条件再判断
if 1==2:
print("1等于2")
elif 1<2:
print("1小于2")
#输出 1小于2
3.else
捕获上述条件中未被捕获的内容
if 1==2:
print("1等于2")
elif 1>2:
print("1大于2")
else:
print("1小于2")#输出 1小于2
循环语句
1.for循环
循环序列(列表、元组、字典、集合或字符串)对其中的项目执行相应的操作
for x in "apple": print(x) ''' 输出 a p p l e '''
2.while循环
条件为真就可以执行代码块里的语句
x = 1
while x<4:
print(x)
x += 1
'''
输出
1
2
3
'''
break语句
使用break语句,指定符合某个条件时终止整个循环
x = 0
while x < 4:
print(x)
x += 1
if x == 3:
break
'''
输出
0
1
2
'''
continue语句
使用continue语句,满足指定条件时会跳过continue之后的语句,继续下一个迭代
x = 0
while x < 4:
x += 1
if x == 3:
continue
print(x)#跳过 x = 3
'''
输出
1
2
4
'''
循环后的else
可以在循环结束时执行else代码块,else语句前有break语句就不会执行
x = 1
while x<4:
print(x)
x += 1
else:
print("Finally finished.")
'''
输出
1
2
3
Finally finished.
'''
range()函数
range()函数会返回一个数字序列,参数为一个数字时,默认从0开始递增1,直到指定数字后结束。也可以指定数字范围和每次增加的数,从起始数字递增至结束数字。
for x in range(5):
print(x)
'''
输出
0
1
2
3
4
注意 最后输出的不是5
'''
for x in range(1,5):
print(x)
'''
输出
1
2
3
4
最后输出的是结束数字-1
'''
for x in range(1,10,2):#2为每次增加的数
print(x)
'''
输出
1
3
5
7
9
'''
Try Except
try块测试代码块的错误
except块处理错误
不论try和except块的结果如何,finally块的代码都会执行。
异常处理1.指定finally块
try:
print(x)#x 未定义
except:
print("Something went wrong")#处理错误,返回一个语句
finally:
print("The 'try except' is finished.")
'''输出
Something went wrong
The 'try except' is finished.
```
2.使用else语句定义未引发错误时将执行的代码块
try:
x = 10
print(x)
except:
print("Something went wrong")#处理错误,输出一个语句
else:
print("Nothing went wrong")
'''输出
10
Nothing went wrong
'''
引发异常
可以指定条件,使用raise关键字+异常,来抛出异常。
x = -1
if x < 0:
raise Exception("Sorry, the number is out of range.")
# Exception: Sorry, the number is out of range.
函数
函数在被调用是执行,可以将数据作为参数传给函数,函数可以返回执行结果。
创建函数1.使用def关键字定义函数
def my_function():
print("It's my function.")
2.调用函数
使用 函数名()
def my_function()
print("It's my function.")
my_function()
#输出 It's my function.
3.参数
函数的参数可以是是任意数量的,也可以是任何数据类型,但是会在函数内部被视作相同的数据类型。参数之间用逗号分隔。
def names(name):
print("The name is "+name+".")
names("Jiang")#输出 The name is Jiang.
names("Lotus")#输出 The name is Lotus.
####Parameters or Arguments
parameters:函数定义中括号内列出的变量(形参)
arguments:调用函数时传给函数的值(实参)
参数数量调用函数时,传入的参数数量必须与函数定义时的参数数量相同
def my_function(name1,name2):
print(name1+" and "+name2+" are good friends.")
my_function("Jiang","Lotus")
#输出 Jiang and Lotus are good friends.
任意参数*args
不能确定有多少参数传到函数中时,在函数中定义的参数名前加*,如此,函数将接收一个元组参数
def my_function(*name):
print(name[2]+" is sweetest.")
my_function("Lorry","Cherry","Jerry")
#输出 Jerry is sweetest.
关键字参数
可以用key = value传递参数,可以不按定义时的参数顺序传递
def my_function(name1,name2): print(name1+" and "+name2+" are good friends.") my_function(name2 = "Jiang",name1 = "Lotus") #输出 Lotus and Jiang are good friends.任意关键字参数**kwargs
不能确定有多少关键字参数传到函数中,在函数中定义的参数前加**,如此,函数将接受一个字典参数
def my_function(**item): print(items["name"]+" is "+items["price"]+" yuan.") my_function(name = "milk",price = "5") #输出 The milk is 5 yuan.默认参数值
在函数定义时,设置参数名并赋值,调用函数时,若无参数传入,则传入默认参数
def my_hometown(h = "Chinese"):
print("I come from "+h+".")
my_hometown()#输出 I come from Chinese.
my_hometown("Norway")#输出 I come from Norway.
返回值
使用return语句使函数返回值
def my_function(x):
return x*2
print(my_function(3))
#输出 6
pass语句
函数未定义内容,但是函数定义不能为空,需要加入pass语句避免出错
def my_function():
pass
递归
在函数内部又对自身进行调用,使代码更简洁,但是对时间和空间的消耗程度大
def my_function(x):
if x > 0:
y = x - my_function(x-1)
return y
else:
return 0
print(my_function(3))#输出 2
Lambda函数
lambda是一个匿名函数,可以接受任意数量的参数,但是只有一个表达式,执行表达式后就会返回一个结果。
语法变量 = lambda 参数: 表达式 (通过变量间接调用Lambda函数)
x = lambda a,b,c : a * b * c
print(x(1,2,3))#输出 6
def my_function(a):
return lambda b : a * b
myNumber = my_function(3)#参数a变成3
print(myNumber(4))#参数b变成4 输出 12
类&对象
python是一种面向对象的编程语言。
对象里含有属性(可以用来描述状态、特征,比如名字、地址、颜色等)和方法(描述动作,比如计算利率等)
将多个对象具有的相同属性、方法抽出来放到一个类里,就是将对象抽象化的过程。创建了某个类的对象,就是将类实例化的过程。
类的创建使用关键字class
class MyClass:
x = 5
对象的创建
创建一个MyClass类的对象
class MyClass:
x = 5
myClass = MyClass()
print(myClass.x)#输出 5
init()函数
所有类都有一个init()函数(构造函数),在类初始化的时候执行,可以使用init()函数给对象属性赋值,或者其他在创建对象是需要进行的操作
class Student:
#init前后是两个_
def __init__(self, name, sex, year):
self.name = name
self.sex = sex
self.year = year
s = Student("Mike","male",20)#初始化时 传入参数
print(s.name)#输出 Mike
print(s.sex)#输出 male
print(s.year)#输出 20
对象方法
在类中创建一个方法,创建一个该类的对象后,该对象包含该方法
class Student:
#init前后是两个_
def __init__(self, name, sex, year):
self.name = name
self.sex = sex
self.year = year
def hello(self):
print("Hello, I am "+self.name+".")
s = Student("Mike","male",20)
s.hello()#输出 Hello, I am Mike.
self参数
self参数是对类当前的实例的引用,用于访问属于该类的对象,这个参数可以自定义命名,但必须是类中函数的第一个参数
class Student:
#init前后是两个_
def __init__(self, name, sex, year):
self.name = name
self.sex = sex
self.year = year
def hello(h):
print("Hello, I am "+h.name+".")
s = Student("Mike","male",20)
s.hello()#输出 Hello, I am Mike.
修改对象属性
s.name = "Marry"#引用.属性删除对象属性
使用del关键字删除对象的属性
del s.sex print(s.sex) #'Student' object has no attribute 'sex' Student类中没有sex属性删除对象
print(s)#输出s指向的内存地址 del s print(s) #name 's' is not defined 引用s无法被识别继承
一个类(子类,也称为派生类)继承另一个类(父类)的所有属性和方法
父类任何类都可以是父类
子类1.创建子类时,将父类作为子类的参数
class Person:
def __init__(self, name):
self.name = name
def printName(self):
print("The name is "+self.name+".")
class Student(Person):
pass#可以不用再写父类中的属性和方法
s = Student("Mike")
s.printName()#输出 The name is Mike.
2.子类中使用构造函数init()调用父类的构造函数
class Student(Person):
def __init__(self,name):
Person.__init__(self, name)#类名引用或者super()
super().__init__(name)#使用super()不需要再写self参数
子类中增加属性
class Student(Person):
def __init__(self,name, sex):
super().__init__(name)
self.sex = sex#增加sex属性
s = Student("Mike","male")
s.printName()#输出 The name is Mike.
子类中增加方法
class Student(Person):
def __init__(self,name, sex):
super().__init__(name)
self.sex = sex#增加sex属性
def deleteName(self):
print("delete "+self.name)
s = Student("Mike","male")
s.printName()#输出 The name is Mike.
s.deleteName()#输出 delete Mike
python迭代器
迭代器是可以迭代的对象(如 list, tuple, dictionary, set 等),可以遍历所有值,由iter()和next()组成.
iter()方法可以进行初始化等操作,返回迭代器对象本身
next()方法执行操作,并且返回序列的一项
class Number:
def __iter__(self):
self.a = 1#初始化
return self
def __next__(self):
x = self.a
self.a += 1#a递增
return x#返回当前a
myNumber = Number()
myIter = iter(myNumber)#调用iter()方法,传入迭代器myNumber
print(next(myIter))#调用next()方法
print(next(myIter))
print(next(myIter))
'''
输出
1
2
3
'''
停止迭代
如果next()方法中没有终止条件,遍历myIter时,就会无限进行。为了防止迭代永远进行,可以指定条件,不满足条件后就会使用StopIteration语句进行终止。
class Number:
def __iter__(self):
self.a = 1#初始化
return self
def __next__(self):
if self.a <= 10:
x = self.a
self.a += 1#a递增
return x#返回当前a
else:#self.a = 11时 就会终止迭代
raise StopIteration
myNumber = Number()
myIter = iter(myNumber)#调用iter()方法,传入迭代器myNumber
for x in myIter:
print(x)
'''
输出
1
2
3
4
5
6
7
8
9
10
'''
模块
模块实质上就是python源代码(其中含有函数)文件,以.py为文件拓展名
#这是一个python源代码文件hello.py
person = {
"name" = "Jerry",
"age" = 18,
}
def sayHello(name):
print("Hello, "+name)
使用模块
使用import语句
#这是一个python源代码文件hello.py
person = {
"name" = "Jerry",
"age" = 18,
}
def sayHello(name):
print("Hello, "+name)
import hello
hello.sayHello("Larry")#调用模块中的方法 输出 Hello, Larry
print(hello.person["age"])#打印模块中的变量 输出 18
从模块中导入部分内容
使用from关键字
#从模块hello中导入person集合 from hello import person print(person["name"])#输出 Jerry print(person["age"])#输出 18文件处理
可以使用open()函数处理文件,open()的第一个参数为文件名,第二个参数为模式.
主要模式:
-
“r”:读取(read)文件 文件不存在会报错(可以用来检查文件是否存在)
-
“a”:追加(append)到文件末尾 文件不存在就会以第一个参数命名并创建文件
-
“w”:写入(write)覆盖文件所有内容 文件不存在就会以第一个参数命名并创建文件
-
“x”:创建指定的文件 文件已经存在就返回错误
-
“t”:文本模式
-
“b”:二进制模式
#hello.txt hello, Mikey! What are you donging here?
f = open("hello.txt","r")
print(f.read())#read()方法返回整个文本
'''
输出
hello, Mikey!
What are you donging here?
'''
#只读取文件的一部分,可以指定要返回的字符数
f = open("hello.txt","r")
print(f.read(5))
'''
输出
hello
'''
#读取一行
f = open("hello.txt","r")
print(f.readline())
'''
输出
hello, Mikey!
'''
f = open("hello.txt","r")
for x in f:
print(x)#循环打印每一行
'''
输出
hello, Mikey!
What are you donging here?
'''
关闭文件
close()函数
f.close()写入现有文件
向open()函数中添加一个参数:
1."a"追加到文章末尾
f = open("hello.txt","a")
f.write("just have a walk.")
f.close()
f = open("hello.txt","r")
print(f.read())
f.close()
'''
输出
hello, Mikey!
What are you donging here?just have a walk.
'''
2."w"写入的内容覆盖原有内容
f = open("hello.txt","w")
f.write("hello")
f.close()
f = open("hello.txt","r")
print(f.read())
f.close()
'''
输出
hello
'''
创建新文件
“x”“a”“w”
文件不存在时,就会创建新文件
f = open("hi.txt","x")
删除文件
必须导入OS模块,执行os.remove()函数
import os
os.import("hi.txt")
检查文件是否存在
删除文件之前为避免错误可以先检查文件中是否存在
import os
if os.path.exists("hi.txt"):#存在才能删除
os.remove("hi.txt")
else:
print("The file didn't exist")



