本文档由脑图导出,地址:http://naotu.baidu.com/file/caceda5851ebccee143af9deeba8de86
参考:heima
[TOC]
python基础
python-基础语法
认识 Python
Python 的起源
解释器(科普)
Python 的设计目标
Python 的设计哲学
为什么选择 Python?
Python 特点
Python 的优缺点
第一个 Python 程序
第一个 HelloPython 程序
常见BUG
手误
将多条写在一行
缩进错误
python 2.x 默认不支持中文
Python 2.x 与 3.x 版本简介
执⾏ Python 程序的三种方式
解释器 python / python3
交互式运行 Python 程序
官方的解释器器
IPython
IDE —— PyCharm
PyCharm 的初始设置
基本使用
程序的注释和算术运算符
注释
单行注释:#
多行注释:””” “””
算数运算符
算数运算符常用
算数运算符的优先级
程序执行原理
变量
基本使用
demo
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 29 30 31 32
| qq_number = "123456" print(qq_number)
price = 8.5 weight = 7.5 money = weight * price money = money - 5 print(money)
name = "小明" age = 18 gender = True height = 1.75
age_str = input("请输入你的年龄:") age_int = int(age_str) print(type(age_int)) print(age_int)
age = float(input("请输入你的分数:")) print(type(age)) print(age)
name = "小明" print("我叫%s" % name) num = 2 print("编号:d" % num) print("我叫%s,编号d" % (name, num)) print("哈" * 10)
|
变量定义
变量的类型
分类
1 2 3 4 5 6 7 8 9 10 11 12 13
| - 数字型 - 整型 (int) - 浮点型(float) - 布尔型(bool) - 真 True 非 0 数 —— 非零即真 - 假 False 0 - 复数型 (complex) - 主要用于科学计算,例如:平面场问题、波动问题、电感电容等问题 - 非数字型 - 字符串 - 列表 - 元组 - 字典
|
不同类型变量之间的计算
1 2 3 4
| 1) 数字型变量 之间可以直接计算 2) 字符串变量 之间使用 + 拼接字符串 3) 字符串变量 可以和 整数 使用 * 重复拼接相同的字符串 4) 数字型变量 和 字符串 之间 不能进行其他计算
|
变量的输入
变量的格式化输出
变量的命名
变量进阶
变量的引用
可变和不可变类型
局部变量和全局变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| num = 10
def demo1():
print("demo1" + "-" * 50) global num num = 100 print(num)
def demo2():
print("demo2" + "-" * 50) print(num)
demo1() demo2()
print("over") `
|
判断(if)语句
demo
```python
if
or and not elif
age = 19
if age >= 18 and age < 30:
print(“已成年”)
print(“ha ha ha”)
else:
print(“未成年”)
print(“喵”)
##
age = 17
if not age > 18:
print(“未成年”)
##
holiday_name = “平安夜”
if holiday_name == “情人节”:
print(“买玫瑰”)
print(“看电影”)
elif holiday_name == “平安夜”:
print(“买苹果”)
print(“吃大餐”)
elif holiday_name == “生日”:
print(“买蛋糕”)
else:
print(“每天都是节日啊……”)
if 的嵌套
定义布尔型变量 has_ticket 表示是否有车票
has_ticket = True
定义整数型变量 knife_length 表示刀的长度,单位:厘米
knife_length = 20
首先检查是否有车票,如果有,才允许进行 安检
if has_ticket:
print(“有车票,可以开始安检…”)
# 安检时,需要检查刀的长度,判断是否超过 20 厘米
# 如果超过 20 厘米,提示刀的长度,不允许上车
if knife_length >= 20:
print("不允许携带 %d 厘米长的刀上车" % knife_length)
# 如果不超过 20 厘米,安检通过
else:
print("安检通过,祝您旅途愉快……")
如果没有车票,不允许进门
else:
print(“大哥,您要先买票啊”)
随机数
import random
num = random.randint(10, 20)
print(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 27 28 29 30 31 32 33 34 35 36 37 38
| #### if 语句体验
#### 逻辑运算
#### if 语句进阶
##### elif
##### if 的嵌套
### 运算符
#### 算数运算符
#### 比较(关系)运算符
#### 逻辑运算符
#### 赋值运算符
#### 运算符的优先级
### 循环
#### demo
```python # 打印 5 遍 Hello Python i = 1 while i <= 5: print("Hello Python") i = i + 1 print("循环结束后的 i = %d" % i)
# break 和 continue - break 某一条件满足时,退出循环,不再执行后续重复的代码 - continue 某一条件满足时,不执行后续重复的代码
|
while 循环基本使用
break 和 continue
while 循环嵌套
九九乘法表
函数
函数基础
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import m_01_hello m_01_hello.print_hello() print(m_01_hello.name)
def say_hello(): """打招呼""" print("hello 函数")
say_hello()
def sum_2_num(num1, num2): result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
sum_2_num(50, 20)
def sum_2_num(num1, num2): """对两个数字的求和"""
return num1 + num2
result = sum_2_num(10, 20)
print("计算结果是 %d" % result)
def test1(): print("*" * 50) print("test 1") print("*" * 50)
def test2(): print("-" * 50) print("test 2")
test1()
print("-" * 50)
test2()
|
快速体验
1 2 3 4 5 6 7 8
| def print_hello(): print("hello") print("python")
import m_01_hello m_01_hello.print_hello()
|
函数基本使用
函数的定义
函数调用
函数的文档注释
函数的参数
函数参数的使用
函数的返回值
函数的嵌套调用
使用模块中的函数
Pyc 文件:模块速度优化
函数进阶
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| gl_num_list = [6, 3, 9]
gl_num_list.sort() print(gl_num_list)
gl_num_list.sort(reverse=True) print(gl_num_list)
def print_info(name, gender=True): gender_text = "男生" if not gender: gender_text = "女⽣" print("%s 是 %s" % (name, gender_text))
""" 1、必须保证 带有默认值的缺省参数 在参数列列表末尾 2、在 调⽤用函数时,如果有 多个缺省参数,需要指定参数名,这样解释器器才能够知道参数的对应关 系! """
def demo(num, *args, **kwargs): print(num) print(args) print(kwargs)
demo(1, 2, 3, 4, 5, name="⼩明", age=18, gender=True)
def sum_numbers(*args): num = 0 for n in args: num += n return num print(sum_numbers(1, 2, 3))
def demo(*args, **kwargs): print(args) print(kwargs)
gl_nums = (1, 2, 3) gl_xiaoming = {"name": "小明", "age": 18}
demo(*gl_nums, **gl_xiaoming)
|
函数参数和返回值的作⽤用
函数的返回值 进阶
函数的参数 进阶
不可变和可变的参数
缺省参数
多值参数
函数的递归
高级变量类型
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| name_list = ["zhangsan", "lisi", "wangwu"]
""" In [1]: name_list. name_list.append name_list.count name_list.insert name_list.reverse name_list.clear name_list.extend name_list.pop name_list.sort name_list.copy name_list.index name_list.remove """
for name in name_list: print(name)
info_tuple = ("zhangsan", 18, 1.75) info_tuple = () info_tuple = (50, )
""" info.count info.index """
for item in info_tuple: print(item)
""" list(元组) tuple(列表) """
""" 字典 是 无序 的对象集合 """
xiaoming = {"name": "小明", "age": 18, "gender": True, "height": 1.75}
""" In [1]: xiaoming. xiaoming.clear xiaoming.items xiaoming.setdefault xiaoming.copy xiaoming.keys xiaoming.update xiaoming.fromkeys xiaoming.pop xiaoming.values xiaoming.get xiaoming.popitem """
for k in xiaoming:
print("%s: %s" % (k, xiaoming[k]))
card_list = [{"name": "张三", "qq": "12345", "phone": "110"}, {"name": "李四", "qq": "54321", "phone": "10086"} ]
string = "Hello Python"
for c in string: print(c)
""" In [1]: hello_str. ... 判断类型 查找和替换 大小写转换 文本对齐 去除空白字符 拆分和连接 """
num_str = "0123456789"
print(num_str[2:6])
print(num_str[2:])
print(num_str[:6])
print(num_str[:])
print(num_str[::2])
print(num_str[1::2])
print(num_str[-1])
print(num_str[2:-1])
print(num_str[-2:])
print(num_str[::-1])
""" len(item) del(item) max(item) min(item) cmp(item1, item2) """
""" [1, 2] + [3, 4] [1, 2, 3, 4] ["Hi!"] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 3 in (1, 2, 3) True 4 not in (1, 2, 3) True (1, 2, 3) < (2, 2, 3) True """
""" for 变量 in 集合: 循环体代码 else: 没有通过 break 退出循环,循环结束后,会执行的代码 """
|
列表(List)
列表的定义
列表常用操作
循环遍历
应用场景
元组(Tuple)
元组的定义
元组常用操作
循环遍历
应用场景
元组和列表之间的转换
字典(dictionary)
字典的定义
字典常用操作
循环遍历
应用场景
字符串
字符串的定义
字符串的常用操作
字符串的切片
公共方法
Python 内置函数
切片
运算符
完整的 for 循环语法
综合应用 —— 名片管理系统
python-面向对象
面向对象(OOP)基本概念
类和对象
面相对象基础语法
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| print(dir(5))
""" class 类名:
def 方法1(self, 参数列表): pass def 方法2(self, 参数列表): pass
对象变量 = 类名() """ class Cat: """这是一个猫类"""
def eat(self): print("小猫爱吃鱼")
def drink(self): print("小猫在喝水")
tom = Cat() tom.drink() tom.eat()
class Cat:
def eat(self): print("%s 爱吃鱼" % self.name)
tom = Cat() tom.name = "Tom" tom.eat()
lazy_cat = Cat() lazy_cat.name = "大懒猫" lazy_cat.eat()
class Cat: """这是一个猫类"""
def __init__(self): print("初始化方法")
my_cat = Cat()
class Cat:
def __init__(self): print("这是一个初始化方法")
self.name = "Tom"
def eat(self): print("%s 爱吃鱼" % self.name)
tom = Cat() tom.eat()
class Cat:
def __init__(self, name): print("初始化方法 %s" % name) self.name = name
tom = Cat("Tom")
lazy_cat = Cat("大懒猫")
""" __del__ 对象被从内存中销毁 前,会 自动 调用 __del__ 方法 __str__ 希望使用 print 输出 对象变量 时,能够打印 自定义的内容,就可以利用 __str__ 这个内置方法了 """
class Cat:
def __init__(self, new_name):
self.name = new_name
print("%s 来了" % self.name)
def __del__(self):
print("%s 去了" % self.name)
def __str__(self): return "我是小猫:%s" % self.name
tom = Cat("Tom--") print(tom)
|
dir 内置函数
定义简单的类
方法中的 self 参数
初始化方法
内置方法和属性
del
str
面向对象封装案例
身份运算符
1 2 3 4 5 6 7 8 9
| """ is 用于判断 两个变量 引用对象是否为同一个 == 用于判断 引用变量的值 是否相等 """ a = [1, 2, 3] b = [1, 2, 3] print(b is a ) print(b == a)
|
私有属性和私有方法
demo
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 29 30 31 32
|
""" 在 属性名或者方法名前 增加 两个下划线,定义的就是 私有 属性或方法
""" class Women:
def __init__(self, name):
self.name = name self.__age = 18
def __secret(self): print("我的年龄是 %d" % self.__age)
xiaofang = Women("小芳")
""" Python 中,并没有 真正意义 的 私有 使用这种方式可以外部访问私有:在 名称 前面加上 _类名 => _类名__方法/属性名 但 不推荐使用 """ xiaofang._Women__secret()
|
应用场景及定义方式
伪私有属性和私有方法
继承
demo
1 2 3 4 5 6
| class 类名(父类名):
pass
class 子类名(父类名1, 父类名2...) pass
|
单继承
继承的概念、语法和特点
方法的重写
父类的 私有属性 和 私有方法
多继承
多继承的使用注意事项
新式类与旧式(经典)类
多态
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Dog(object):
def __init__(self, name): self.name = name
def game(self): print("%s 蹦蹦跳跳的玩耍..." % self.name)
class XiaoTianDog(Dog):
def game(self): print("%s 飞到天上去玩耍..." % self.name)
|
类属性和类方法
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
""" @classmethod def 类方法名(cls): pass
由 哪一个类 调用的方法,方法内的 cls 就是 哪一个类的引用 """ @classmethod def show_tool_count(cls): """显示工具对象的总数""" print("工具对象的总数 %d" % cls.count)
""" @staticmethod def 静态方法名(): pass """
""" 需求 1、设计一个 Game 类 2、属性: 定义一个 类属性 top_score 记录游戏的 历史最高分 定义一个 实例属性 player_name 记录 当前游戏的玩家姓名 3、方法: 静态方法 show_help 显示游戏帮助信息 类方法 show_top_score 显示历史最高分 实例方法 start_game 开始当前玩家的游戏 """
class Game(object): top_score = 0
@staticmethod # 静态方法 def show_help(): print("帮助信息:让僵尸走进房间")
@classmethod # 类方法 def show_top_score(cls): print("游戏最高分是 %d" % cls.top_score)
def __init__(self, player_name): self.player_name = player_name
def start_game(self): print("[%s] 开始游戏..." % self.player_name)
Game.top_score = 999
Game.show_help()
Game.show_top_score()
game = Game("小明")
game.start_game()
Game.show_top_score()
|
类的结构
类属性和实例属性
类方法和静态方法
单例
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class MusicPlayer(object):
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None: cls.instance = super().__new__(cls)
return cls.instance
class MusicPlayer(object):
instance = None init_flag = False
def __new__(cls, *args, **kwargs):
if cls.instance is None: cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
if not MusicPlayer.init_flag: print("初始化音乐播放器")
MusicPlayer.init_flag = True
player1 = MusicPlayer() print(player1)
player2 = MusicPlayer() print(player2)
|
单例设计模式
new 方法
Python 中的单例
异常
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| """ try: 尝试执行的代码 except: 出现错误的处理 """ try: num = int(input("请输入数字:")) except: print("请输入正确的数字")
""" try: # 尝试执行的代码 pass except 错误类型1: # 针对错误类型1,对应的代码处理 pass except 错误类型2: # 针对错误类型2,对应的代码处理 pass except (错误类型3, 错误类型4): # 针对错误类型3 和 4,对应的代码处理 pass # 如果希望程序 无论出现任何错误,都不会因为 Python 解释器 抛出异常而被终止,可以再增加一个 except except Exception as result: # 打印错误信息 print(result) # else 只有在没有异常时才会执行的代码 else: # 没有异常才会执行的代码 pass # finally 无论是否有异常,都会执行的代码 finally: # 无论是否有异常,都会执行的代码 print("无论是否有异常,都会执行的代码") """
def demo1(): return int(input("请输入一个整数:"))
def demo2(): return demo1()
try: print(demo2()) except ValueError: print("请输入正确的整数") except Exception as result: print("未知错误 %s" % result)
def input_password():
pwd = input("请输入密码:")
if len(pwd) >= 8: return pwd
ex = Exception("密码长度不够")
raise ex
try: user_pwd = input_password() print(user_pwd) except Exception as result: print("发现错误:%s" % result)
|
异常的概念
捕获异常
异常的传递
抛出 raise 异常
模块和包
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| """ import 模块名1 import 模块名2 import 模块名1 as 模块别名 # 通过 模块名. 使用 模块提供的工具 —— 全局变量、函数、类
# 从 模块 导入 某一个工具 from 模块名1 import 工具名 # 可以直接使用 模块提供的工具 —— 全局变量、函数、类
如果 两个模块,存在 同名的函数,那么 后导入模块的函数,会 覆盖掉先导入的函数
# 从 模块 导入 所有工具 # 这种方式不推荐使用,因为函数重名并没有任何的提示,出现问题不好排查 from 模块名1 import *
__name__ 属性 __name__ 属性可以做到,测试模块的代码 只在测试情况下被运行,而在 被导入时不会被执行! __name__ 是 Python 的一个内置属性,记录着一个 字符串 如果 是被其他文件导入的,__name__ 就是 模块名 如果 是当前执行的程序 __name__ 是 __main__ """
def main(): pass
if __name__ == "__main__": main()
""" 1、新建一个 hm_message 的 包 2、在目录下,新建两个文件 send_message 和 receive_message 3、在 send_message 文件中定义一个 send 函数 4、在 receive_message 文件中定义一个 receive 函数 5、在外部直接导入 hm_message 的包
"""
from . import send_message from . import receive_message
import m_message m_message.receive_message.receive() m_message.send_message.send()
|
模块
包(Package)
发布模块
制作发布压缩包步骤
安装模块
pip 安装第三方模块
文件
demo
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| """ open,read,write,close
当执行了 read 方法后,文件指针 会移动到 读取内容的末尾
f = open("文件名", "访问方式")
"""
file = open("README")
text = file.read() print(text)
file.close()
f = open("README", "w")
f.write("hello python!\n") f.write("今天天气真好")
f.close()
file = open("README")
while True: text = file.readline()
if not text: break
print(text, end="")
file.close()
file_read = open("README") file_write = open("README[复件]", "w")
text = file_read.read() file_write.write(text)
file_read.close() file_write.close()
file_read = open("README") file_write = open("README[复件]", "w")
while True: text = file_read.readline()
if not text: break
file_write.write(text)
file_read.close() file_write.close()
""" 创建、重命名、删除、改变路径、查看目录内容、…… 需要导入 os 模块 例如:os.rename(源文件名, 目标文件名) """
|
文件的概念
文件的基本操作
文件/目录的常用管理操作
文本文件的编码格式
ASCII 编码和 UNICODE 编码
Ptyhon 2.x 中如何使用中文
eval 函数
demo
1 2 3 4 5 6 7 8
| """ eval() 函数十分强大 —— 将字符串 当成 有效的表达式 来求值 并 返回计算结果 eval("1 + 1") """
input_str = input("请输入一个算术题:") print(eval(input_str))
|