python的基础语法
字面量
注释
数据类型转换
运算符
字符串扩展
字符串格式化
字符串格式化-快速写法
掌握input(函数)的使用
判断语句
if判断语句
循环语句
while循环
i = 1
while i < 10:
j = 1
while j < 1+i:
jieguo = j*i
print(f"{j}*{i}={jieguo}\t ", end='')
j += 1
print()
i += 1
for循环
name = "inheima"
for x in name:
print(x)
range语句
# 99乘法表
for i in range(1,10):
for j in range(1,11-i):
print(f"\t{i}*{j}={i*j}" ,end='')
print("")
循环中断
函数
函数的定义
def add(x, y):
result = x+y
print(f"{x}+{y}={result}")
add(1,3)
函数返回值中的None类型
函数的说明文档
global关键字
使用global关键字可以在函数内部声明变量为全局变量
num = 100
def test():
global num
num = 200
print(num)
test()
print(num)
数据容器
函数的定义
函数功能(方法)
查询元素
mylist =["itcast","itheima", "python"]
index = mylist.index("itcast")
print(f"itcast的列表下表索引值为{index}")
插入元素
追加单个元素
追加一批元素
删除元素
方法一: del列表[下标]
mylist =["itcast","itheima", "python"]
# 方法一
del mylist[2]
print(mylist)
方法二: 列表.pop(下标),也可以通过pop方法取出元素并返回给一个值
mylist =["itcast","itheima", "python"]
# 方法二
mylist.pop(2)
print(mylist)
mylist =["itcast","itheima", "python"]
# 方法二
element = mylist.pop(2)
print(element)
方法三:查询删除
方法四:清空列表
统计元素数量
统计指定元素数量
统计所有的元素总数
列表的遍历
while循环遍历
mylist =["itcast","itheima", "python"]
index = 0
while index < len(mylist):
element = mylist[index]
print(element)
index = index + 1
for循环遍历
mylist =["itcast","itheima", "python"]
index = 0
for element in mylist:
print(element)
元组
元组一旦形成就不可更改
字符串
replace方法(字符串的替换)
my_str = "itheima and itcast"
# replace方法
new_my_str = my_str.replace("it","程序")
print(new_my_str)
split方法(字符串的分割)
my_str = "hello python itheima itcast"
my_str_list = my_str.split(" ")
print(my_str_list)
序列的切片
列表,元组,字符串都属于是序列
my_list = [1,2,3,4,5,6,7,8,9]
result = my_list[1:4:1]
print(result)
# 结果为[2,3,4]
set集合
集合的定义
特点:
- 无序
- 不可重复
提取随机元素
提取差集
消除差集
集合合并
字典
特点:
不允许重复,若字典中有重复值,则重复值覆盖前面的定义
字典的嵌套
my_dict1 = {
"王力宏":{
"语文":88,
"数学":77,
"英语":66
},"周杰伦":{
"语文": 89,
"数学": 89,
"英语": 95
},"林俊杰":{
"语文": 84,
"数学": 65,
"英语": 47
}}
print(my_dict1["王力宏"]["语文"])
字典的常规操作
my_dict = {"张学友":99,"周杰伦":88,"林俊杰":77}
# 新增元素
my_dict["张信哲"] = 66
print(my_dict)
# 更新元素
my_dict["张学友"] = 33
print(my_dict)
# 删除元素
my_dict.pop("张学友")
print(my_dict)
# 清空元素
my_dict.clear()
print(my_dict)
my_dict = {"张学友":99,"周杰伦":88,"林俊杰":77}
for key in my_dict:
print(key,my_dict[key])
类数据容器的总结
数据容器的通用操作
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
my_str = "abcdefg"
my_set = {1, 2, 3, 4, 5}
my_dict = {"key1": 1, "key2": 2, "key3":3}
# len元素个数
print(f"列表 元素个数为{len(my_list)}")
print(f"元组 元素个数为{len(my_tuple)}")
print(f"字符串 元素个数为{len(my_str)}")
print(f"集合 元素个数为{len(my_set)}")
print(f"字典 元素个数为{len(my_dict)}")
# max最大元素
print(f"列表 元素个数为{max(my_list)}")
print(f"元组 元素个数为{max(my_tuple)}")
print(f"字符串 元素个数为{max(my_str)}")
print(f"集合 元素个数为{max(my_set)}")
print(f"字典 元素个数为{max(my_dict)}")
# min最小元素
print(f"列表 元素个数为{min(my_list)}")
print(f"元组 元素个数为{min(my_tuple)}")
print(f"字符串 元素个数为{min(my_str)}")
print(f"集合 元素个数为{min(my_set)}")
print(f"字典 元素个数为{min(my_dict)}")
my_list = [5, 4, 8, 6, 9]
my_tuple = (5, 4, 8, 6, 9)
my_str = "bcfjshf"
my_set = {5, 4, 8, 6, 9}
my_dict = {"key3": 1, "key1": 2, "key2":3}
#排序
print(f"列表对象的排序结果为 {sorted(my_list)}")
print(f"元组对象的排序结果为 {sorted(my_tuple)}")
print(f"字符串对象的排序结果为{sorted(my_str)}")
print(f"集合对象的排序结果为 {sorted(my_set)}")
print(f"字典对象的排序结果为 {sorted(my_dict)}")
#反向排序
print(f"列表对象的反向排序结果为 {sorted(my_list, reverse=True)}")
print(f"元组对象的反向排序结果为 {sorted(my_tuple, reverse=True)}")
print(f"字符串对象反向的排序结果为{sorted(my_str, reverse=True)}")
print(f"集合对象的反向排序结果为 {sorted(my_set, reverse=True)}")
print(f"字典对象的反向排序结果为 {sorted(my_dict, reverse=True)}")
函数进阶
多个返回值
def test_return():
return 1,2
x,y = test_return()
print(x,y)
函数的多种传参方式
位置参数
关键字参数
缺省参数
不定长参数
- 位置传递
- 关键字传递
匿名函数
以函数作为参数传递
def test_return(compute):
result = compute(1, 2)
print(result)
def compute(x ,y):
return x+ y
test_return(compute)
lambda匿名函数语法
lambda匿名函数
def test_return(compute):
result = compute(1, 2)
print(result)
test_return(lambda x, y: x +y)
文件操作
文件的读取操作
f = open("D:/测试.txt","r",encoding="UTF-8")
# 只读文件 - read()
print(f"只读取十个字节的内容{f.read(10)}")
print(f"读取全部的内容{f.read()}")
# 读取文件 - readLines()
lines = f.readlines()
print(f"读取全部的内容{lines}") # 读取的文件的全部涵盖,封装在列表中
# 读取文件 - readline()
line1 = f.readline()
line2 = f.readline()
line3 = f.readline()
print(f"line1: {line1}")
print(f"line2: {line2}")
print(f"line3: {line3}")
# for 循环读取文件行
for line in f:
print(line)
# 文件的关闭
f.close()
with open("D:/测试.txt","r",encoding="utf-8") as f:
for line in f:
print(line)
写出操作
f = open("D:/测试.txt","w",encoding="UTF-8")
# 注意w模式是,文件不存在会创建一个文件,若文件存在则会删除原来的文件创建新文件
# write 写入
f.write("hello world") # 内容写到内存中
# flush刷新
f.flush() # 将内存中积攒的内容,写入到硬盘的文件中
# close关闭
f.close() # close方法,内置了flush的功能
文件的追加
f = open("D:/测试.txt","a",encoding="UTF-8")
# write 写入
f.write("hello world") # 内容写到内存中
# flush刷新
f.flush() # 将内存中积攒的内容,写入到硬盘的文件中
# close关闭
f.close() # close方法,内置了flush的功能
异常,模块与包
异常
捕获异常的作用在于: 提前假设某处会出现异常,做好提前准备,当真的出现异常的时候,可以有后续手段。
try:
f = open("D:/测试.txt","r",encoding="UTF-8")
except:
print("出现异常了,文件不存在,将open的模式改为w模式去打开")
f = open("D:/测试.txt","w",encoding="UTF-8")
# 捕获指定异常
try:
print(name)
except NameError as e:
print("出现了变量未定义的异常")
# eles没有异常是执行的代码
try:
f = open("D:/测试.txt","r",encoding="UTF-8")
except:
print("出现异常了,文件不存在,将open的模式改为w模式去打开")
f = open("D:/测试.txt","w",encoding="UTF-8")
else:
print("没有异常时执行的代码")
# finally无论有没有异常都会去执行的代码
try:
f = open("D:/测试.txt","r",encoding="UTF-8")
except:
print("出现异常了,文件不存在,将open的模式改为w模式去打开")
f = open("D:/测试.txt","w",encoding="UTF-8")
finally:
print("我是finally")
f.close()
模块
Python模块(Module): 是一个Python文件,以.py结尾,模块能定义函数,类和变量,模块里也可以包含指定代码。
import time # 导入Python内置的time模块(time.py这个代码文件
print("睡眠前")
time.sleep(5)
print("睡眠后")
import time as tt # 给导入到模块起别名
print("睡眠前")
tt.sleep(5)
print("睡眠后")
from time import sleep #导入模块中的其中一个方法
print("睡眠前")
sleep(5)
print("睡眠后")
from time import * # 导入模块中的所有方法
print("睡眠前")
sleep(5)
print("睡眠后")
自定义模块
_ _ main _ _ 变量
if __name__ == '__main__':
# 在这写的代码不会被调用
_ _ all _ _变量
安装第三方包
"-i pypi.tuna.tsinghua.edu.cn/simple"
数据可视化
JSON数据格式
什么是JSON:
- JSON是一种轻量级的数据交互格式。可以按照JSON指定的格式去组织和封装数据
- JSON本质上是一个带有特定格式的字符串
主要功能: JSON就是一种在各个编辑语言中流通的数据格式,负责不同编辑语言中主句传递和交互
import json
data = [{"name":"张大山","age":11},{"name":"王大锤","age":13},{"name":"赵小虎","age":14}]
# ensure_ascii=False 用来转化成中文
# 准备列表将列表转换成JSON类型
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)
print(type(json_str))
# 准备字典将字典转换成JSON类型
d = {"name":"周杰伦","adde":"台北"}
json_str = json.dumps(d, ensure_ascii=False)
print(json_str)
print(type(json_str))
# 将JSON字符串转换成Python类型
c = '[{"name":"张大山","age":11},{"name":"王大锤","age":13},{"name":"赵小虎","age":14}]'
l = json.loads(c)
print(l)
print(type(l))
pyecharts模块
可以去“gallery.pyecharts.org”网站去查询想要的图形
# 基础折线图
from pyecharts.charts import Line
# 得到折线图对象
line = Line()
# 添加x轴数据
line.add_xaxis(["中国","美国","英国"])
# 添加y轴对象
line.add_yaxis("GDP",[30,20,10])
# 生成图表
line.render()
puecharts模块中有很多配置选项
- 全局配置选项
# 基础折线图
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts
# 得到折线图对象
line = Line()
# 添加x轴数据
line.add_xaxis(["中国","美国","英国"])
# 添加y轴对象
line.add_yaxis("GDP",[30,20,10])
# 设置全局配置项set_global_opts来设置
line.set_global_opts(
title_opts=TitleOpts(title="GDP展示",pos_left="center",pos_bottom="1%"),
legend_opts = LegendOpts(is_show=True),
toolbox_opts = ToolboxOpts(is_show=True),
visualmap_opts= VisualMapOpts(is_show=True),
)
# 生成图表
line.render()
- 系列配置选项
line.add_yaxis("GDP",[30,20,10], label_opts=LabelOpts(is_show=False))
具体内容去官网去查看
面向对象
初识对象
# 1.设计一个类
class student:
name = None
gender = None
nationality = None
native_place = None
age = None
# 2.创建一个对象
stu_1 = student()
# 3.对象的属性进行赋值
stu_1.name = "林俊杰"
stu_1.gender = "男"
stu_1.nationality = ("中国")
stu_1.native_place = ("山东省")
stu_1.age =31
# 4.获取对象中记录的信息
print(stu_1.name)
print(stu_1.gender)
print(stu_1.nationality)
print(stu_1.native_place)
print(stu_1.age)
类的成员方法
成员变量
成员方法
# 1.设计一个类
class student:
name = None
def say_hello(self):
print(f"Hello,我是{self.name}")
# 2.创建一个对象
stu_1 = student()
# 3.对象的属性进行赋值
stu_1.name = "林俊杰"
# 4.获取对象中记录的信息
stu_1.say_hello()
构造方法
# 1.设计一个类
class student:
def __init__(self,name,age,tel):
self.name = name
self.age = age
self.tel = tel
# 2.创建一个对象
stu_1 = student("周杰伦",31,18500006666)
# 3.获取对象中记录的信息
print(stu_1.name)
print(stu_1.age)
print(stu_1.tel)
常见的魔术方法
上面的构造方法就是其中一种
- 字符串方法
# 1.设计一个类
class student:
def __init__(self,name,age):
self.name = name
self.age = age
# __str__魔术方法
def __str__(self):
return f'student类对象,name:{self.name},age:{self.age} '
stu = student("周杰伦",31)
print(stu) # student类对象,name:周杰伦,age:31
- _ _ lt _ _ 小于符号的比较方法
# 1.设计一个类
class student:
def __init__(self,name,age):
self.name = name
self.age = age
# __lt__小于符号比较
# other代表另一个对象
def __lt__(self, other):
return self.age < other.age
stu1 = student("周杰伦",11)
stu2 = student("林俊杰",13)
print(stu1 < stu2) # Ture
print(stu2 < stu1) # False
- _ _ le _ _小于等于比较符号方法
class student:
def __init__(self,name,age):
self.name = name
self.age = age
# __le__小于符号比较
# other代表另一个对象
def __le__(self, other):
return self.age <= other.age
stu1 = student("周杰伦",11)
stu2 = student("林俊杰",11)
print(stu1 <= stu2)
print(stu2 <= stu1)
- _ _ eq _ _ 比较运算符实现方法
# 1.设计一个类
class student:
def __init__(self,name,age):
self.name = name
self.age = age
# __le__小于符号比较
# other代表另一个对象
def __eq__(self, other):
return self.age == other.age
stu1 = student("周杰伦",11)
stu2 = student("林俊杰",11)
print(stu1 == stu2)
print(stu2 == stu1)
封装
面向程序设计,是许多编程语言都支持的一种编程思想。
简单理解就是:基于模版(类)去创建实体(对象),使用对象完成功能开发。
面向对象包含三大主要特性:
- 封装
- 继承
- 多态
私有成员
- 私有成员变量:变量名以_ _开头(两个下划线)
- 私有成员方法:方法名以_ _开头(两个下划线)
# 1.设计一个类
class Phone:
__current_voltage = 0 # 当前手机运行电压
def __keep_single_core(self):
print("让CPU以单核形式运行")
def call_by_5g(self):
if self.__current_voltage >= 1:
print("5g通话已开启")
else:
self.__keep_single_core()
print("电量不足,无法使用5g通话,并已设置为单核运行进行省电")
phone = Phone()
phone.call_by_5g()
继承
单继承
# 1.设计一个类
class Phone:
IMEI =None
producer = "HM"
def call_by_4g(self):
print("4g通话")
class Phone2022(Phone):
face_id = "10001"
def call_by_5g(self):
print("2022年新功能")
phone = Phone2022()
print(phone.producer)
phone.call_by_5g()
phone.call_by_4g()
多继承
# 1.设计一个类
class Phone:
IMEI =None
producer = "HM"
def call_by_4g(self):
print("4g通话")
class Phone2022(Phone):
face_id = "10001"
def call_by_5g(self):
print("2022年新功能")
# 多继承
class Phonex(Phone2022,Phone):
print("实现多继承")
phone = Phonex()
phone.call_by_5g()
phone.call_by_4g()
对于父类中同名方法或属性,先继承的优先级大于后继承的
复写
在子类中定于与父类相同的方法
# 1.设计一个类
class Phone:
IMEI =None
producer = "HM"
def call_by_4g(self):
print("4g通话")
# 复写
class Phone2022(Phone):
producer = "ITHM"
def call_by_4g(self):
print("2022年新功能")
phone = Phone2022()
print(phone.producer)
phone.call_by_4g()
在子类中调用父类的方法
# 1.设计一个类
class Phone:
IMEI =None
producer = "HM"
def call_by_4g(self):
print("4g通话")
# 复写
class Phone2022(Phone):
producer = "ITHM"
def call_by_4g(self):
# 调用父类父类
# 方法一
print(Phone.producer)
Phone.call_by_4g(self)
# 方法二
print(super().producer)
super().call_by_4g()
phone = Phone2022()
phone.call_by_4g()
多态
多态,指的是:多种状态,即完成某个行为时,使用不同的的对象和得到不同的状态。
# 演示抽象类
class AC:
def cool_wind(self):
"""制冷"""
pass
def hot_wind(self):
"""制热"""
pass
def swing_l_r(self):
"""左右摆风"""
pass
class Midea_AC(AC):
def cool_wind(self):
print("美的空调制冷")
def hot_wind(self):
print("美的空调制热")
def swing_l_r(self):
print("美的空调左右摆风")
class GREE_AC(AC):
def cool_wind(self):
print("格力空调制冷")
def hot_wind(self):
print("格力空调制热")
def swing_l_r(self):
print("格力空调左右摆风")
def make_cool(ac :AC):
ac.cool_wind()
midea_ac = Midea_AC()
gree_ac = GREE_AC()
make_cool(midea_ac)
make_cool(gree_ac)
注解
类型注解
类型注释的主要功能室是:
- 帮助第三方工具对代码进行类型推断,协助做代码提示
- 帮助开发者自身对变量进行类型注释
通过Ctrl+P可以查看需要输入的数据类型
# 基础数据类型注解
import random
var_1: int = 10
var_2: str = "itheima"
var_3: bool = True
# 类对象类型注解
class Student:
pass
stu: Student = Student()
# 基础容器类型注解
ma_list: list = [1,2,3]
my_tuple: tuple = (1,2,3)
my_dict: dict = {"name":666}
# 容器类型详细注解
my_list: list[int] = [1,2,3]
my_tuple: tuple[int,str,bool] = (1,"itheima",True)
my_dict: dict[str,int] = {"name":666}
# 在注释中进行类型的注解
var_4 = random.randint(1,10) # type:int
函数的方法类型注解
# 对形参进行类型注解
def add(x: int, y: int):
return x+y
print(add(1, 2))
# 对返回值进行注解
def func(data: list) ->list:
return data
Union联合类型注解
Union联合类型注解,在变量注解.函数(方法).形参返回值注解中均可使用。
# 注意导包
from typing import Union
my_list: list[Union[int, str]] = [1,2,"itheima","itcast"]
def func(data: list[Union[int, str]]) -> Union[int, str]:
pass
func()
python操作数据库的基础使用
先下载pymysql的数据包
查询性SQL
from pymysql import Connection
# 构建到Mysql数据库连接
conn = Connection(
host='localhost',
port=3306,
user='root',
password='123456'
)
# print(conn.get_server_info())
# 执行非查询性SQL
cursor = conn.cursor() # 获得游标对象
# 选择数据库
conn.select_db('user')
# 执行数据库
cursor.execute("create table test_pysql(id int);")
# 关闭连接
conn.close()
非查询性SQL
from pymysql import Connection
# 构建到Mysql数据库连接
conn = Connection(
host='localhost',
port=3306,
user='root',
password='123456'
)
# print(conn.get_server_info())
# 执行非查询性SQL
cursor = conn.cursor() # 获得游标对象
# 选择数据库
conn.select_db('user')
# 执行数据库
cursor.execute("select * from page")
results = cursor.fetchall()
for row in results:
print(row)
# 关闭连接
conn.close()
mySQL数据插入
from pymysql import Connection
# 构建到Mysql数据库连接
conn = Connection(
host='localhost',
port=3306,
user='root',
password='123456',
# 2.设置自动提交
autocommit=True
)
# print(conn.get_server_info())
# 执行非查询性SQL
cursor = conn.cursor() # 获得游标对象
# 选择数据库
conn.select_db('user')
# 执行数据库
cursor.execute("insert into page values (1,'周杰伦','123456')")
# 1.通过commit确认
# conn.commit()
# 关闭连接
conn.close()