Python学习(是我的课堂上学到的东西)不包含课外

复习

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
"""
复习变量标识符
"""

# 组成的限制
name = "xieleihan"
_name = "xieleihan"
address_01 = "Hong kong"
# 有些不能使用的变量名
# 01_address = "Canton"
# 区分大小写

age = 28
Age = 40
# 不用关键字
Class = "2024级"
# 报错的原因:不能使用关键字
# class = "2024级"
# 命名规范
stu_id = 120
stu_name = "xieleihan"
stu_age = 28
# 不规范的用法就是使用了中文拼音
nianling = 28
xb = "男"
print(nianling,xb)

# 变量的命名规范
# 1. 变量名只能由字母、数字、下划线组成
# 2. 变量名不能以数字开头
# 3. 变量名不能是python的关键字
# 4. 变量名不能是python内置的名字
# 5. 变量名不能是中文
# 6. 变量名不能和关键字冲突
# 7. 变量名不能和已定义的变量冲突
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""
算术运算符的使用
"""

a = 20
b = 10
# 加法运算符
print(a,"+",b,"=",a+b)
# 减法运算符
print(a,"-",b,"=",a-b)
# 乘法运算符
print(a,"*",b,"=",a*b)
# 除法运算符
print(a,"/",b,"=",a/b)
# 取余运算符
print(a,"%",b,"=",a%b)
# 幂运算符
print(a,"**",b,"=",a**b)
# 取整运算符
print(a,"//",b,"=",a//b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
逻辑运算符的使用方法
"""

# and
print(True,"and",True,"=",True and True)
print(True,"and",False,"=",True and False)
print(False,"and",True,"=",False and True)
print(False,"and",False,"=",False and False)

# or
print(True,"or",True,"=",True or True)
print(True,"or",False,"=",True or False)
print(False,"or",True,"=",False or True)
print(False,"or",False,"=",False or False)

# not
print(not True,"=",not True)
print(not False,"=",not False)
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
"""
Python的输入输出函数
"""

# 输出函数
print("Hello World")
# 输入函数
name = input("请输入你的名字:")

# 简化后的输入输出
age = int(input("请输入你的年龄:"))
salary = float(input("请输入你的工资:"))
# 格式化输出
print("你的名字是:%s,你的年龄是:%d,你的工资是:%.2f" % (name, age, salary))
# 查看类型函数
print(f"{type(name), type(age), type(salary)}")
# 数据类型转换
# int()
age = int(input("请输入你的年龄:"))
# float()
salary = float(input("请输入你的工资:"))
# str()
name = str(input("请输入你的名字:"))
print(f"你的名字是:{name},你的年龄是:{age},你的工资是:{salary}")

# 输入函数
# 输入函数的功能是从键盘获取用户的输入,并将用户的输入返回给程序。
# 输入函数的格式:
# input()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
基础语法练习
"""

# 下面主要是对输入的三门成绩进行求和和求平均
name = input("请输入你的名字:")
chinese = int(input("请输入你的语文成绩:"))
math = int(input("请输入你的数学成绩:"))
english = int(input("请输入你的英语成绩:"))
# 格式化先打印
print("你好,%s,你的语文成绩是:%d,数学成绩是:%d,英语成绩是:%d" % (name, chinese, math, english))
# 计算平均分
average = (chinese + math + english) / 3
print("你的平均分是:%.2f" % average)
# 计算总分
total = chinese + math + english
print("你的总分是:%d" % total)
# 全部打印
print("你好,%s,你的语文成绩是:%d,数学成绩是:%d,英语成绩是:%d,你的平均分是:%.2f,你的总分是:%d" % (name, chinese, math, english, average, total))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
分支语句
"""

# if 语句
age = input("请输入你的年龄:")
age = int(age)
if age <= 18:
print("未成年")
elif age < 30:
print("青年")
elif age < 50:
print("中年")
else:
print("老年")
1
2
3
4
5
6
7
8
9
"""
登录操作(简单)
"""

# 这个不能用于企业级
if input("请输入用户名:") == "admin" and input("请输入密码:") == "123456":
print("登录成功")
else:
print("登录失败")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
月份季节的练习
"""

# 对输入的月份进行输出对应的季节
mouth = int(input("请输入月份:"))
if mouth == 1 or mouth == 2 or mouth == 12:
print("该月份为春季")
elif mouth == 3 or mouth == 4 or mouth == 5:
print("该月份为夏季")
elif mouth == 6 or mouth == 7 or mouth == 8:
print("该月份为秋季")
elif mouth == 9 or mouth == 10 or mouth == 11:
print("该月份为冬季")
else:
print("输入的月份有误")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
随机生成一个1-10的随机数,给用户3次机会看是否可以猜中
"""

import random

target = random.randint(1, 10)
if int(input("请输入一个1-10的数字:")) == target:
print("恭喜你,猜中了!1")
elif int(input("请输入一个1-10的数字:")) == target:
print("恭喜你,猜中了!2")
elif int(input("请输入一个1-10的数字:")) == target:
print("恭喜你,猜中了!3")
else:
print(f"你输了,再接再厉!目标数字:{target}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
跑步练习
"""

day = 1
# 外层循环
while day <= 7:
print(f"周{day}跑步")
distance = 1
# 内层循环
while distance <= 5:
print(f"第{distance}公里", end=" ")
distance += 1
day += 1
print()
print("跑步结束")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
数字序列
"""

# 数字序列
# Python中可以使用range()函数返回一个数字序列
# range(n) return one [0,n)
# range(m,n) return one [m,n)
# range(m,n,s) return one [m,n,s)

# 示例
for i in range(10):
print(i)

# 输出1-50之间所有偶数
for i in range(2, 51, 2):
print(i)

for num in range(1, 51):
if num % 2 == 0:
print(num)
print("over")
1
2
3
4
5
6
7
8
9
10
11
"""
使用for循环实现九九乘法表的输出
"""

# 外层循环控制行
for i in range(1, 10):
# 内层循环控制列
for j in range(1, i+1):
# 输出九九乘法表
print(f"{j}*{i}={j*i}\t", end=" ")
print()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
break and continue 关键字
"""

# break 关键字
# break 关键字的作用是跳出当前循环,结束循环。
for i in range(10):
if i == 5:
break
print(i)

# continue 关键字
# continue 关键字的作用是跳过当前循环,继续下一次循环。
for i in range(10):
if i == 5:
continue
print(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""
函数的内容
"""

# 自定义带参数有返回值的函数
def shopping(money, name, price, count):
pay_money = price * count
return_money = money - pay_money
if return_money >= 0:
print(f"购物小票\n商品名称:{name}\n商品单价:{price}\n商品数量:{count}\n商品总价:{pay_money}")
return return_money
else:
print("余额不足,请充值")
return -1

# 函数调用:接收返回值
money = shopping(100, "苹果", 10, 2)
print(f"找零:{money}")
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
"""
函数递归
"""

# 计算数据n的阶乘
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
# 输入要计算的数
n = int(input("请输入要计算的数:"))
# 函数调用
result = factorial(n)
# 输出
print("阶乘结果为:", result)

# 计算第n个斐波那契数列
def fibonacci_num(n):
if n == 1 or n == 2:
return 1
else:
return fibonacci_num(n - 1) + fibonacci_num(n - 2)
# 输入要计算的位置
n = int(input("请输入要计算的位置:"))
# 函数调用
result = fibonacci_num(n)
# 输出
print("第", n, "个斐波那契数列为:", result)
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
"""
函数参数传递
"""

def position_param(name, age, isMarry):
print(f"姓名:{name} 年龄:{age} 是否结婚:{isMarry}")

# 位置传参
position_param("张三", 18, True)
def keyword_param(name, age, isMarry):
print(f"姓名:{name} 年龄:{age} 是否结婚:{isMarry}")

# 关键字传参: 形参名 = 实参名 支持乱序传递
keyword_param(isMarry=True, age=18, name="张三")

# 位置传参和关键字传参混合使用
keyword_param("张三", 18, isMarry=True)

def default_param(name, age, isMarry=False):
print(f"姓名:{name} 年龄:{age} 是否结婚:{isMarry}")
# 默认值传参
default_param("nm",18)
default_param("nbcs",20,True)
# 可变参数(位置传参)
def sum(*args):
# 参数以元组方式进行存储
print(f"参数:{args} 类型:{type(args)}")
sum = 0
for i in args:
sum += i
return sum
# 调用可变参数函数(位置传参)
result = sum(1,2,3,4,5,6,7,8,9,10)
print(f"1-10累加和:{result}")
# 可变参数(关键字传参)
def staff_info(**kwargs):
print(f"参数:{kwargs} 类型:{type(kwargs)}")
# 调用可变参数函数(关键字传参)
staff_info(name="张三", age=18, isMarry=True)
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
"""
ATM
"""

# 存款
def set_money(num):
global money
if num > 0:
money += num
print(f"存款成功,{num}元")
else:
print("存款失败")
# 取款
def get_money(num):
global money
if money >= num:
money -= num
print(f"取款成功,{num}元")
else:
print("取款失败")
# 查询
def query_money():
print(f"余额:{money}元")
# 登录
def login():
global name
name = input("请输入你的姓名:")
psw = input("请输入你的密码:")
if "lvzhitian" == name and "123456" == psw:
global tag
tag = True
else:
tag = False
print("登录失败")
login()
print(f"欢迎{name}登录")
# home
def home():
print("1.存款\n2.取款\n3.查询\n4.退出")
op = int(input("请输入你的选择:"))
if op == 1:
set_money(int(input("请输入存款金额:")))
home()
elif op == 2:
get_money(int(input("请输入取款金额:")))
home()
elif op == 3:
query_money()
home()
elif op == 4:
print("退出")
else:
print("输入有误")

# 定义全局变量
money = 10000
name = None
tag = False

# 登录
login()
# 循环
# while tag:
# home()
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
"""
数据容器CRUD
"""

# 定义一个空列表
list = []
print(list)

# 增
list.append("jack")
list.append("lucy")
print(list)
# 扩展列表
list.extend(["tom", "jerry"])
print(list)
# 插入元素
list.insert(1, "tom")
print(list)

# 改
list[0] = "jack"
list[-1] = "lucy"
print(list)

# 查
print(f"{list}容器中有:{len(list)}个元素")
list.append("andi")
print(f"{list}容器中有:{list.count('jack')}个jack,{list.count('lucy')}个lucy,{list.count('andi')}个andi元素")
# 查找指定元素的索引
print(f"list容器中jack的索引为:{list.index('jack')}")
# 报错
# valueerror:”jack“ is not in list

# 删
# 索引删除
del list[-1]
ele = list.pop(-1)
print(f"删除list容器中最后一个元素:{ele}")
# 元素删除
list.remove("jack")
print(list)

# 清空
list.clear()
print(list)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
将列表【1,2,3,4,5,6,7,8,9,10】中的偶数元素存储到另一个列表
"""
# 数据列表
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 自定义函数
def get_even_num(data):
# 定义一个空列表
result = list()
# 遍历数据列表
for num in data:
# 判断数据是否为偶数
if num % 2 == 0:
# 将偶数添加到结果列表中
result.append(num)
# 返回结果列表
return result
# 调用函数
x = get_even_num(data)
# 输出结果
print(x)
# [2, 4, 6, 8, 10]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
字典的遍历
"""

# 定义字典
dict = {"python":100,"java":90,"c++":70}

# key遍历
for key in dict.keys():
print(f"{key} = {dict[key]}",end=" ")
print()

score = 0

# value遍历
for value in dict.values():
print(f"{value}",end=" ")
score += value
print(f"总分:{score}")

# item遍历
for k,v in dict.items():
print(f"{k} = {v}",end=" ")
print()
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
"""
集合的CRUD
"""
# 空集合
set = set()
print(set, type(set))

# 增
set.add("jack")
set.add("tom")
set.add("adin")
set.add("odin")
# 添加重复值
set.add("jack")

# 改:无法直接获取数据,因此无法修改
# 删:由于无序存储,所以随机删除(多次执行,结果不同)
ele = set.pop()
print(ele)
print(set)

# 查
print(f"{set}中有元素:{len(set)}个")
for ele in set:
print(f"{ele}", end=" ")
print()

# 并集
print({1,2,3,4,5}.union({2,3,4,5,6}))
# 差集
print({1,2,3,4,5}.difference({2,3,4,5,6}))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""
去除列表中重复的元素
"""

result = set()
target = [10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("原始列表:",target)

# 遍历
for ele in target:
result.add(ele)

# 输出
print("去重后的列表:",result)
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
"""
切片
"""

# 列表
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 开始索引
print(list1[4:])

# 结束索引
print(list1[:5])

# 区间索引
print(list1[2:5])

# 反向索引
print(list1[-1::-1])

# 省略索引
print(list1[:])

# 步长
print(list1[::2])
print(list1[1::-2])
print(list1[::-1])
print(list1[::-2])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
敏感词过滤
"""

# 定义敏感词列表
not_words = ['fuck','shit', 'bitch', 'cunt', 'pussy', 'bastard', 'asshole', 'dick', 'boob', 'boobies', 'boobs', 'cock', 'cocks', 'nigger', 'niggers', 'nigga', 'niggas', 'penis', 'penises', 'fucking','shitting', 'bitching', 'cunting', 'pussying', 'bast']
content = input('请输入内容:')

# 过滤
def filter_content(words, string):
for w in words:
string = string.replace(w, '*' * len(w))
return string

print(f"过滤前:{content}")
result = filter_content(not_words, content)
print(f"过滤后:{result}")
1
2
3
4
5
6
7
8
"""
从序列!nohtyP olleH 中提取 python
"""

string = "nohtyP olleH"
sub_str = string[6::-1]
print(string)
print(sub_str)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
文件的拷贝
"""

# 打开文件
fr = open('fuxi25.txt', 'r', encoding='utf-8')
fw = open('fuxi25_copy.txt', 'w', encoding='utf-8')
# 循环遍历
for line in fr:
# 写入一行
fw.write(line)
# 刷新
fw.flush()
fr.close()
fw.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
常见异常
"""

# 名字异常
# print(val)
# 除零异常
# print(12/0)
# 索引异常
# str = "jack"
# print(str[10])
# 值异常
# num = int("jack")
# 类型异常
# print(len(100))
# 文件找不到异常
# open("1.txt", "r",encoding="utf-8")
# 需要执行的代码
print("需要执行的代码")
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
"""
异常处理
"""

try:
# 可能发生valueerror
num1 = int(input("被除数:"))
num2 = int(input("除数:"))
# 可能发生zerodiverror
result = num1 / num2
print(f"{num1} / {num2} = {result}")
except ValueError as e:
print("输入有误,请重新输入")
print(e)
except ZeroDivisionError as e:
print("除数不能为0")
print(e)

# 对上面进行简化
try:
num1 = int(input("被除数:"))
num2 = int(input("除数:"))
result = num1 / num2
print(f"{num1} / {num2} = {result}")
except (ValueError, ZeroDivisionError) as e:
if isinstance(e, ValueError):
print("输入有误,请重新输入")
elif isinstance(e, ZeroDivisionError):
print("除数不能为0")
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
"""
异常处理
"""

file = None
try:
# 可能发生valueerror
num1 = int(input('被除数:'))
num2 = int(input('除数:'))
# 可能发生除零错误
result = num1 / num2
print(f"{num1}/{num2}={result}")
# 可能发生filenotfounderror
file = open('test.txt', 'r',encoding='utf-8')
except (ValueError, ZeroDivisionError, FileNotFoundError) as e:
if isinstance(e, ValueError):
print('输入有误')
if isinstance(e, ZeroDivisionError):
print('除数不能为0')
if isinstance(e, FileNotFoundError):
print('文件不存在')
# 创建该文件
print("创建新文件")
file = open('test.txt', 'w',encoding='utf-8')
file.writelines('hello world')
print(e)
else:
print("读文件数据")
print(file.readline())
finally:
file.close()
print("文件关闭")
1
2
3
4
5
6
7
8
9
10
11
12
13
"""
异常返回值
"""

def exception_return():
try:
# raise Exception('抛出异常')
return 1
except Exception as e:
return 2
else:
return 3
print(exception_return())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
类和对象
"""

# 定义类
class Person:
# 属性
name = None
age = None
friends = None
# 构造函数
def __init__(self, name, age, friends):
self.name = name
self.age = age
self.friends = friends
# 行为(函数)
def introduce(self):
print(f"")
print(f"大家好,我叫{self.name},今年{self.age}岁,我的好朋友是:{self.friends}")
# 定义对象
obj = Person("小明", 20, ["小红", "小黑"])
# 介绍自己
obj.introduce()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
构造函数
"""

class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
print("创建一个学生对象,并做了成员属性")

stu01 = Student("Michael", 20, 98)
stu02 = Student("Bob", 22, 100)
print(f"{stu01.name}的年龄是{stu01.age}成绩是{stu01.score}")
print(f"{stu02.name}的年龄是{stu02.age}成绩是{stu02.score}")
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
"""
魔术方法
"""

class Student:
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score

# __str__:默认输出类和内存地址
def __str__(self):
return f"name={self.name},age={self.age},score={self.score}"

# 默认进行<>会报错
def __lt__(self, other):
return self.score < other.score

# 默认进行<=,>=会报错
def __le__(self, other):
return self.score <= other.score

# 默认==比较的是两对象的内存地址
def __eq__(self, other):
return self.score == other.score

stu01 = Student("zs",18,99)
stu02 = Student("lisi",18,93)
# 默认调用的是__str__魔术方法
print(stu01)
print(str(stu01))
# 默认调用的是__lt__魔术方法
print(stu01 < stu02)
print(stu01 > stu02)
# 默认调用的是__le__魔术方法
print(stu01 <= stu02)
print(stu01 >= stu02)
# 默认调用的是__eq__魔术方法
stu03 = stu01
stu04 = Student("wanwu",18,80)
print(stu03 == stu04)
print(stu01 == stu03)
print(stu01 == stu04)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
封装
"""
class Teacher:
# 封装属性
__id_card = "4542164641164"
# 封装方法
def __verify_edu(self):
print("验证教师资格")
# 封装的信息是内部其他方法使用的
def entry_work(self):
self.__verify_edu()
print(self.__id_card)
print("input")

# 创建对象
teacher = Teacher()
# 访问封装信息出错
# print(teacher.__id_card)
# 访问封装方法出错
# teacher.__verify_edu()
# 调用公开方法
teacher.entry_work()
1
2
3
4
5
6
7
8
9
10
11
12
13
"""
继承
"""

class Father:
def __init__(self):
print("father构造函数")
class Son(Father):
def __init__(self):
Father().__init__(self)
print("son构造函数")

son = Son()
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
"""
继承的练习
"""

class Staff:
id = None
name = None
def __init__(self, id, name):
self.id = id
self.name = name
print("Staff构造函数")

class Father:
children_name = None
children_age = None
def __init__(self, children_name, children_age):
self.children_name = children_name
self.children_age = children_age
print("Father构造函数")

class Teacher(Staff, Father):
def __init__(self, id, name, children_name, children_age):
Staff.__init__(self, id, name)
Father.__init__(self, children_name, children_age)
print("Teacher构造函数")
def __str__(self):
return f"{self.id},{self.name},{self.children_name},{self.children_age}"

t = Teacher(1, "张三", "李四", 18)
print(t)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
SQL语句
"""
"""
--插入数据
insert into student (id,name,age,gender) values
(1,"jack",24,'男'),
(2,"luck",30,'女'),
(3,"jack1",124,'男'),
(4,"luck1",130,'女');
-- 查询数据
select * from student;
-- 修改数据
update student set age = 30 where id = 3;
-- 删除数据
delete from student where id = 1;
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
数据库连接
"""

from pymysql import Connection
# 获取数据库连接
conn = Connection(
host='localhost',
port=2280,
user='root',
password='password',
db='python',
charset='utf8'
)
# 打印对象
print(conn)
# 获取主机信息
print(conn.get_host_info())
# 获取数据库版本
print(conn.get_server_info())
# 关闭连接
conn.close()