Python

108 阅读14分钟

python的基础语法

字面量

bb10e5b621fd7cf698c457662b554bb.jpg

注释

948fa4cdc3f9cd37522656186114cf0.jpg

数据类型转换

ce9d85df0223a596b07abd06de4479f.jpg

运算符

a291ff3de95cd397e85e83b9809ef35.jpg

4245397af7dde6b21618027d5d4a5aa.jpg

字符串扩展

字符串格式化

d51f9f65a9ca8f2a7efcdb6fdaffeb9.jpg

14885322ce4deebe1f78425a2cf66fc.jpg

字符串格式化-快速写法

8cf5c36282d880215da21c02544d519.jpg

掌握input(函数)的使用

3d1e8c8a1cfab1294debf46d78b160d.jpg

判断语句

if判断语句

1031e861f2b6840d1a1ed40d7f155db.jpg

循环语句

while循环

11d82b3a0077b711ec0a86cf909859e.jpg

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循环

5bb9785a28ef5b6c46158554af94b3a.jpg

name = "inheima"

for x in name:
    print(x)

range语句

4150aacca6b7f34732103858308df98.jpg

536cf9d4c75dcd007afc82d206d57ce.jpg

# 99乘法表
for i in range(1,10):
    for j in range(1,11-i):
        print(f"\t{i}*{j}={i*j}" ,end='')

    print("")

循环中断

1ef603054c7ae97d0563cd041e35ed8.jpg

612ca31948078f612913e461323fc87.jpg

函数

函数的定义

24d0ee5ce6c5c31fe7d58210b314d63.jpg

def add(x, y):
    result = x+y
    print(f"{x}+{y}={result}")

add(1,3)

函数返回值中的None类型

881df98f4f98a6bf016854544562e51.jpg

函数的说明文档

00ac9ffd1976ffdabf4b6134e7ce30d.jpg

global关键字

使用global关键字可以在函数内部声明变量为全局变量

num = 100
def test():
    global num
    num = 200
    print(num)

test()
print(num)

数据容器

03220f54a9a243dcd0fc5263e59db22.jpg

函数的定义

bfb5a0ae3303b27cee4c12eefceaaac.jpg

函数功能(方法)

查询元素

7cdc9b40c993c6a69c51c9e203a061a.jpg

mylist =["itcast","itheima", "python"]

index = mylist.index("itcast")
print(f"itcast的列表下表索引值为{index}")

插入元素

c0adaa8a78d4b7eb8b49f5716a30248.jpg

追加单个元素 b35d719e4ebee9febcc43dd2cf4f997.jpg

追加一批元素 168b8713df2cb8e74a5bea3e9d6a553.jpg 删除元素

方法一: 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)

方法三:查询删除

adcbece23a1ff071f383e0fd0581b49.jpg

方法四:清空列表

dd59adabb80e610f165113bdab9bbc2.jpg

统计元素数量

统计指定元素数量 c0474db71477d08c1b23179e8cc248f.jpg

统计所有的元素总数 2a259f32fa85c02ac3c48c3f61c4995.jpg

列表的遍历

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)

元组

元组一旦形成就不可更改

3f75281e86ac598502487b1f2de30c1.jpg

字符串

83748d8cc63e365b58b2b2fbbdc7e0e.jpg

replace方法(字符串的替换)

7d4ac9ecb7d57ff2e49eb062a6f92cb.jpg

my_str = "itheima and itcast"

# replace方法
new_my_str = my_str.replace("it","程序")
print(new_my_str)

split方法(字符串的分割)

5a1e3b2b11ec41e327e68f1108c6e11.jpg

my_str = "hello python itheima itcast"

my_str_list = my_str.split(" ")
print(my_str_list)

image.png

序列的切片

列表,元组,字符串都属于是序列 58fb6b1a38e283f8a61e61a471c21a3.jpg

my_list = [1,2,3,4,5,6,7,8,9]
result = my_list[1:4:1]
print(result)
# 结果为[2,3,4]

set集合

集合的定义 a8de68146fc50c339ed02700bec2dea.jpg

特点:

  • 无序
  • 不可重复

提取随机元素 e6112c6cbf43163559aff30151a0f3c.jpg

提取差集 0e2dab420154f1553fba6ea6e7057be.jpg

消除差集 f2cd84fd507860f14764d695df1bcdd.jpg

集合合并

364068dc8141cf6ff279b63124dcee1.jpg

字典

2f41d5da1aeb03843efe1ffb9fd701e.jpg 特点: 不允许重复,若字典中有重复值,则重复值覆盖前面的定义

字典的嵌套

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])

类数据容器的总结

19e118e8bc7009b321847d5b415f148.jpg

数据容器的通用操作

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)}")

5947d6aaeb3231cb64b2280eff3221c.jpg

函数进阶

多个返回值

def test_return():
    return 1,2

x,y = test_return()
print(x,y)

函数的多种传参方式

位置参数 4e2ba712c30c202dd265cbe82a03f81.jpg 关键字参数 178a2511d59a8ff344ccd977dd56a26.jpg 缺省参数 f46aa6c901a7d9af797f0af5af6abf1.jpg 不定长参数 5c35b607f6cd3c72812b4b8c059a1f5.jpg

  • 位置传递 d66cb10813b2ab07ffe6f56a4ab235e.jpg
  • 关键字传递 8a2a88cbf0a84f37ff2cb24f53454fc.jpg

匿名函数

以函数作为参数传递

def test_return(compute):
    result = compute(1, 2)
    print(result)

def compute(x ,y):
    return x+ y

test_return(compute)

lambda匿名函数语法

lambda匿名函数

a2022f7dc9017d052e2d2dc82e5a514.jpg

def test_return(compute):
    result = compute(1, 2)
    print(result)

test_return(lambda x, y: x +y)

文件操作

文件的读取操作

e3f4f38767913255354836872665877.jpg

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()

ec31d3e07e54c071c582157d61fdff1.jpg

with open("D:/测试.txt","r",encoding="utf-8") as f:

    for line in f:
        print(line)

写出操作

3518937dfa7d98b0d3db8294a633f62.jpg

f = open("D:/测试.txt","w",encoding="UTF-8")
# 注意w模式是,文件不存在会创建一个文件,若文件存在则会删除原来的文件创建新文件

# write 写入
f.write("hello world") # 内容写到内存中

# flush刷新
f.flush()  # 将内存中积攒的内容,写入到硬盘的文件中

# close关闭
f.close()  # close方法,内置了flush的功能

文件的追加

3518937dfa7d98b0d3db8294a633f62.jpg

f = open("D:/测试.txt","a",encoding="UTF-8")

# write 写入
f.write("hello world") # 内容写到内存中

# flush刷新
f.flush()  # 将内存中积攒的内容,写入到硬盘的文件中

# close关闭
f.close()  # close方法,内置了flush的功能

异常,模块与包

异常

捕获异常的作用在于: 提前假设某处会出现异常,做好提前准备,当真的出现异常的时候,可以有后续手段。

c023fdf711f5dcaa86cd70ae7b125ed.jpg

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结尾,模块能定义函数,类和变量,模块里也可以包含指定代码。

44705e7a1134857aa1d47a7ec31ebdf.jpg

import time    # 导入Python内置的time模块(time.py这个代码文件

print("睡眠前")
time.sleep(5)
print("睡眠后")


import time as tt  # 给导入到模块起别名

print("睡眠前")
tt.sleep(5)
print("睡眠后")

e86fb76f5443462a1be9286fd32adf8.jpg

from time import sleep #导入模块中的其中一个方法
print("睡眠前")
sleep(5)
print("睡眠后")

4879b15aefa5dab47f49d7065a4997a.jpg

from time import *  # 导入模块中的所有方法
print("睡眠前")
sleep(5)
print("睡眠后")

自定义模块

_ _ main _ _ 变量

if __name__ == '__main__':
# 在这写的代码不会被调用

_ _ all _ _变量

181a768d5d11d2c651c99501109fbd9.jpg

安装第三方包

9e84c44fba4162aa59a3bebf93275a0.jpg

"-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)

类的成员方法

成员变量 66fdddee29c15d8aa5cb9536d9e186e.jpg

成员方法 8188e7d4ac5b5d160667e54cc17127b.jpg

# 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()

构造方法

dbb1b94833a4724bc3ff017b73036c3.jpg

# 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. 字符串方法
# 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 
  1. _ _ 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
  1. _ _ 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)
  1. _ _ 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()