第一节

摘要:
本文摘要: Python基础语法与变量学习笔记,包含以下核心内容: 基础语法 注释使用(单行#,多行"“”) print函数使用(换行\n、分隔符sep、格式化输出%d/%s/%.2f) 变量基础 变量定义与赋值(单变量/多变量同时赋值) 变量修改(可跨类型修改) 命名规则(下划线/驼峰命名法) 数据类型 整型、浮点型(保留小数位) 布尔型(True/False判断) 字符串(索引操作、拼接/重复运算) 实践案例 购物金额计算 猴子分香蕉问题 股票盈亏模拟 包含常量定义、关键字查询等实用技巧,适合Python入学者

基础语法

"""
    主要讲解:初识 python的基础语法
"""

# 2026-03-26 开始学习python
# 打印数字
print(2026)

# 打印字符串
print("hello world ...")
print('hello world ...')

print("我是块注释....")  # 行注释

print("我是多行注释开始 ... ")
"""
    我是多行注释。。。。。。
"""
print("我是多行注释的结束 ... ")

"""
1,主要讲解 python 的换行、替换、保留几位小数

"""

print("开始学习 print()函数:输出/打印指定内容")
# print(*objects, sep=' ', end='\n', file=None, flush=False)
print("################## 任务1 ##################")
"""
    任务1:
    打印数字 2024
    任务2:
    打印字符串 开始学习python
    任务3:
    创建变量year,变量值为2024
    打印变量year
"""
print(2024)
print("开始学习python")
year = 2024
print(year)

print("################## 任务2 ##################")
"""
    任务2:
    我是小土豆
    2024年,我要减肥
    
    2024年,我要读100本书
    
    2024年,我要去10个城市旅游
    
    今天是2024年02月22日,星期五,今天的天气 晴,气温 15.5 度
"""
year = 2024
month = 2
day = 2
weather = "晴"
temperature = 15.5
print("我是小土豆")
# \n 是换行符  \n\n 表示换行2个
'''
    sep='' 设置打印多个内容的分割符
    比如用之前是:2024 年,我要去10个城市旅游
    用之后是:2024年
'''
print(year, "年,我要减肥", sep="", end="\n\n")
print(year, "年,我要读100本书", sep='', end='\n')
print(year, "年,我要去10个城市旅游")
'''
    %d 替换 数值
    %s 替换 字符串
    %f 替换 浮点型的数值, %.2f:保留2位小数值
    执行结果: 今天是2024年02月2日,星期五,今天的天气是 晴 ,气温 15.50 度
'''
print("今天是%d年%02d月%d日,星期五,今天的天气是 %s ,气温 %.2f 度" % (year, month, day, weather, temperature),  sep="")

第二节

变量

"""
    day02: python 变量
    2.1
"""
name = '老张'
age = 18
major = '校长'
hobby = '我爱上班'
pet_phrase = '诺诺,大大,我也想吃这个,就喜欢跟大大好'
print(name, age, major, hobby, pet_phrase)

print("------------------------------------------")

"""
    2.2 多个变量的赋值
"""
# 多个变量的值相同
num1 = num2 = num3 = 66
print(num1, num2, num3)

# 多个变量的值不同,元组赋值
phone, email = '15336771810', '15336771810@163.com'
print(phone, email)

print("******************** 【练习1】 **********************")
"""
    变量名 = 变量值
    
    【练习1】
    苹果的价格是 10.5 元/斤
    买了 7.5 斤 苹果
    计算付款金额
"""
price = 10.5
weight = 7.5
print("计算付款金额:", price * weight)

print("******************* 【变量的修改】 ***********************")
# 创建变量后,可以在代码中重新赋值。
salary = 800
print("修改之前salary的:", salary)
salary = 900
print("修改之后的salary:", salary)

# 不同类型的变量也可以进行修改、重新赋值,与类型无关
salaryMoney = "两百"
salaryMoney = '200'
print(salaryMoney)

# 常量学习
classGrade = "2年纪2班"
print("常量是:" + classGrade)

className1, className2, className3 = "小明", "小红", "小小"
print("className1:名字是:%s ,班级是:%s" % (className1, classGrade), sep="")

"""
    标示符:

        标示符可以由 字母、下划线 和 数字 组成
        不能以数字开头
        不能与关键字重名

"""
print("--------------------- 【关键字】 ----------------------")
'''
                【关键字】
    关键字 就是在 Python 内部已经使用的标识符
    关键字 具有特殊的功能和含义
    开发者 不允许定义和关键字相同的名字的标示符

'''

import keyword

print(keyword.kwlist)

'''
    
命名规则 可以被视为一种 惯例,并无绝对与强制 
目的是为了 增加代码的识别和可读性

    在 Python 中,如果 变量名 需要由 【二个 或 多个单词】 组成时,可以按照以下方式命名
    每个单词都使用小写字母
        单词与单词之间使用 _下划线 连接
        例如:first_name、last_name ...
    
    驼峰命名法
    当 变量名 是由2个或多个单词组成时,还可以利用驼峰命名法来命名。
    
    小驼峰式命名法
        第一个单词以小写字母开始,后续单词的首字母大写
        例如:oneDay、lastDay
    
    大驼峰式命名法
        每一个单词的首字母都采用大写字母
        例如:OneDay、LastDay
'''

print("**************** 【变量的数据类型】 ***********************")
'''
    python 定义变量不需要指定类型。
'''
age = 18
stuName = "老张"
print("age的类型是:", type(age))
print("stuName的类型是:", type(stuName))
# 判断age类型是否是 int类型对象、stuName 判断是否是 str类型对象
print(isinstance(age, int))
print(isinstance(stuName, str))

'''
    作业一:
        这里有 10 个香蕉,
        小猴子 吃了 2 个,
        猩猩 吃了 4 个,
        长臂猴 吃了剩下的所有的香蕉。

        我们想知道:
        小猴子 和 猩猩 两个人一共拿走多少香蕉?
        长臂猴 能吃多少香蕉?
'''
bananasTotal = 10
babyMonkey = 2
orangutan = 4
babyMonkeyAndOrangutanSum = babyMonkey + babyMonkey
LongTailedMonkey = bananasTotal - babyMonkeyAndOrangutanSum
print("小猴子 和 猩猩 两个人一共拿走 %d 香蕉" % babyMonkeyAndOrangutanSum)
print("长臂猴 能吃 %d 香蕉" % LongTailedMonkey)

'''
    炒股基金里面有100元。经过了涨幅操作: 
    第一天:涨了 30 元; 
    第二天:亏了 40 元;
    最后清仓还剩多少。
'''
stockTradingFundSum = 100
oneDay = stockTradingFundSum + 30
print("第一天账户余额:", oneDay)
twoDay = oneDay - 40
print("第二天账户余额:", twoDay)

print("********************** 【浮点型】*************************")
# 数据类型:浮点型(Floating point numbers)
num1 = 3.127
num2 = 2.32
sum = num1 + num2
print("num1 + num2 和是没有取小数点的:", sum)
# 针对浮点型数值相加后
print("num1 + num2 相加后取小数点3位%.3f" % sum)
print(type(num1))
print(isinstance(num2, float))

print("********************** 【布尔型】*************************")
'''
    布尔类型的变量只有True、False两种值。
    作用:
        作为真假的判断。
    
    在python中,能够解释为假的值有:
    None、0、0.0、False、所有的空容器(空列表、空元组、空字典、空集合、空字符串)
'''
a, b = True, False
print(a)
print(b)

print("********************** 【字符串】*************************")
'''
    数据类型:字符串(String)
        字符串就是 一串字符,比如'' 或者""引起来的字符串
        或者3个引号 引起来的字符串
'''
str1 = "Hello World"
str2 = ''
print("str1 的数值是:", str1)
print("str2 的数值是:", str2)

print("str1+str2 => ", str1 + str2)
print("str1 *3 => ", str1 * 3)

'''
    字符串的索引:
        索引计数从 0 开始
'''
str3 = "zhang Tea Take care on your journey!"
print(str3[0], str3[1], str3[2])
print(str3)

print("*********** 【开始学习数据类型转换】**************")
'''
    数据类型转换:
        int(x, [基数] )          将数字或字符串转换为整数,如果x为浮点数,则自动截断小数部分
        float(x)                将x转换成浮点型
        bool(x)                 转换成bool类型 的True或 False
        str(x)                  将x转换成字符串,适合人阅读
'''
# 将浮点型转换成int类型
float1 = 6.191219
print(int(float1))

# 将int类型转换成浮点型
int4 = 998
print(float(int4))



# 变量练习
"""
    【练习】修改代码

    今天超市搞活动,只要消费就打8折
    请重新计算购买金额
"""
# 价格
price = 10.5
# 重量
weight = 7.5
# 折扣
discount = 0.8

appliedBefore = price * weight
print("计算打折之前付款金额:", appliedBefore)

appliedAfter = appliedBefore * discount
print("打折之后的价格:", appliedAfter)

第三节

运算

'''
    算术运算 +-*/
        // :取整
        %  :取模
        ** n :幂运算
'''
num1 = 4
num2 = 13
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
# 默认保留1位小数
print(num2 / num1)
#   // :取整
print(num2 // num1)
#  %  :取模
print(num2 % num1)
# 幂运算
print(num1 ** 3)
print(3 + 2 * (4 ** 2))

'''
    赋值运算

'''
num1 = 12
print("num1:", num1)
# 相当于 num1 = num1+2
num1 += 2
print("num1:", num1)

''' 
    比较运算
'''
print(3 == 3)
print(3 != 3)
print(3.0 == 3)
print(True == False)
# 字符串的比较运算:每个字符的 ascii 码值 i>e
print('hello' > 'hi')
print(1 < 2 < 5)
# 相当于 'y' < 'x' and 'x' == False
print('y' < 'x' == False)
print('y' < 'x' and 'x' == False)

'''
    位运算符
'''

'''
按位与&
    2个都是1才是1
5: 101
7: 111
--------
   101 
'''
print(5 & 7)

'''
按位或|
    只要有一个1就是1
3:011
6:110
-------
   111 
'''
print(3 | 6)

'''
按位异或
    对应二进制位 相同为 0,不同为 1。
3:011
4:100
-------
   111 
'''
print(3 ^ 4)

'''
    按位取反
1:01    
---------
   10
    按位取反后得到 ...1110,这是补码表示的 -2。
   
'''
print(~1)

'''
    左移右移
7:111
-------
   11100    
'''
print(7 << 2)


"""
    与、并且 and
"""
print(True and False)
print(True and False and True)
print(1 > 2 and True)
# 短路运算 左边是true取右边的
print('hello' and 'hi')
print(False and 'hi')
print(True and 'hi')
print(0 and 1)
print(True and 0)

print("************ 【或 or】 *************")
'''
    或 or
'''
print(True or False)
print(1 or 0)
print(66 or 88 or 99)
print(0 or '' or 88)

print("************ 【非 not】 *************")
'''
    非 not
'''
print(not True)
print(not False)
# '' 空的字符串是false
print(not '')
print(not 1)

print("************ 【优先级】 *************")
# 优先级 not > and > or
print(True and False or not False)
print(False or (not True) and True)

'''
 成员运算符
    相当于 mysql的 select xx from table where xx in ('xxx','xxx')
'''
print('ac' in 'abcd')
num1 = 1
num2 = 2
print(num1 is num2)
print(num1 is not num2)

第四节

多态

'''
    多分支开发
        日期判断:
            从控制台输入一个数,判断是周几

'''
num = int(input("请输入一个数字:"))
if num == 1:
    print("周一")
elif num == 2:
    print("周二")
elif num == 3:
    print("周三")
elif num == 4:
    print("周四")
elif num == 5:
    print("周五")
elif num == 6:
    print("周六")
elif num == 7:
    print("周日")
else:
    print("请输入正确的时间")


'''
作业一:
    定义一个整数变量 age,编写代码判断年龄是否正确
    要求人的年龄在 0-120 之间
'''
inputAge = int(input("请输入年龄:"))
if 0 <= inputAge < 120:
    print("年龄合法。")
else:
    print("输入有误")

'''
作业二:
    定义两个整数变量 python_score、c_score,编写代码判断成绩
    要求只要有一门成绩 >= 60 分就算合格
'''
inputPythonScore = int(input("请输入python的成绩:"))
inputCScore = int(input("请输入c的成绩:"))
if inputPythonScore >= 60 or inputCScore >= 60:
    print("考试通过")
else:
    print("考试成绩不合格,请重新复习,再补考")

'''
作业三:
    闰年判断
    输入一个年份(大于 1582 的整数 ),判断这一年是否是闰年,如果是输出 1,否则输出 0。
    提示:普通闰年的年份是4的倍数,且不是100的倍数;世纪闰年的年份必须是400的倍数。
'''
inputYear = int(input("请输入年份:"))

if (not inputYear % 4 and inputYear % 100) or not inputYear % 400:
    print(inputYear, "是闰年")
else:
    print(inputYear, "不是闰年")
'''
    Python中的match语句:
        是Python 3.10及以后版本中引入的新特性,用于模式匹配。
        它允许你根据对象的模式来检查对象,并执行相应的代码块
        如果没有匹配成功,则可以选择使用一个默认的代码块,使用下划线_来表示
            类似java的 switch语句
                switch()
                    case: xx
                        break;
                    default:
                        xxx
'''
snack = int(input("今天可以吃零食吗:"))
match snack:
    case 1:
        print("可以吃零食")
    case 0:
        print("不可以吃")
    case _:
        print("你自己看着办")

print("****************************************************")
'''
    判断文档类型
'''
workType = input("请输入文档类型")
match workType:
    case "txt":
        print("文档是txt文本")
    case "pdf":
        print("是pdf类型")
    case "work":
        print("是work类型")
    case "_":
        print("我也不知道啥类型")
'''
    第4章:
        简单条件:
            分支选择结构
'''
rest = '周末'
if rest == '周末':
    print("周末放假好好休息")

print('****************************************')

rest = '周末'
if rest == '周末':
    print("周末放假好好休息")
print('吃顿好的')

print('*******************【简单if else demo】*********************')
rest = '周一'
if rest == '周末':
    print("周末放假好好休息")
else:
    print('加油搬砖')

print('*******************【if elif elif else demo】*********************')

'''
    多种判断
        案例:
            bmi计算 
            bmi=体重(kg)/(身高*身高(米)) 
            标准:
            bmi<18.5 过瘦 
            18.5-23.9 正常 
            >23.9 过胖

'''
weight = float(input("请求输入的你的体重/kg:"))
height = float(input("身高/米:"))
bmi = weight / height ** 2
# %.2f :保留2位小数
print("您的bmi计算结果是:%.2f" % bmi)
if bmi < 18.5:
    print("您太瘦了,多吃点补补")
elif bmi <= 23.9:
    print("正常体重,太棒了")
else:
    print("有点胖了哟,注意下饮食")

第五节

循环

'''
    循环的作用就是让
        指定的代码,重复的执行
    while 循环最常用的应用场景就是 让执行的代码 按照 指定的次数 重复 执行
'''
# 案例一:
# 打印5遍,马年发大财

# 1.定义重复的次数
count = 0
# 使用while循环
while count < 5:
    print("马年发大财")
    count = count + 1
    print("循环结束体:i = %d" % count)

print("***********************************")
# 计算1+2+3+……+100的和
currentNumber = 1
sum = 0
while currentNumber < 101:
    sum += currentNumber
    print("当前计算的是 currentNumber = %d,和sum = %d " % (currentNumber, sum))
    currentNumber += 1


'''
    概念:条件始终为真的循环称为死循环
        循环语句中,表达式永远执行直至磁盘爆满
'''
while True:
    print("我要出去")
'''
练习一:
    range()函数可以用来创建一个数字序列,
    常与for循环结合使用来重复执行代码块指定的次数。
'''
for executeCount in range(10):
    print("current executeCount:%d" % executeCount)

'''
continue:
    作用:跳过本次循环后面的剩余语句,然后继续下一次循环
    注意:只能跳过距离最近的for或者while循环
'''
for i in range(10):
    if i % 2 == 0:
        continue
    print("当前的i %d" % i)
    # print("外面的")




'''
break:
    退出循环
     在循环过程中,如果某一个条件满足后,不再希望循环继续执行,可以使用break退出循环

'''
currentNum = 0
while currentNum < 5:
    currentNum += 1
    #当 currentNum == 3时候,退出循环不再执行
    if currentNum == 3:
        print("当前数值是 %d,准备退出" % currentNum)
        break
    print("当前的currentNum %d" % currentNum)


'''
    作用:
        当语句要求不希望任何命令或者代码执行
    说明:
        pass 表示一个空操作,占位作用
'''
if 1:
    pass

for i in range(10):
    print("i %d" % i)

'''
################【练习】################
练习一:
    打印出m行n列的图形
    *****
    *****
    *****
    *****
'''
m = int(input("请输入你要打印的行数:"))
n = int(input("请输入你要打印的列数:"))
for currentM in range(m):
    for currentN in range(n):
        print("*", end='')
    print()


'''
练习二:
    打印出n行的字符三角形
            *     
           ***   
          *****     
         ******* 
     
   1  1   2n-1
   2  3    2n-1
   3  5    2n-1
   4  7    2n-1
'''
row = int(input("请输入行数:"))
for i in range(row):
    print(' '*(row - 1 - i) + '*'*(i*2+1))


'''
练习三:
    猴子吃桃:
        一只小猴买了若干个桃子。
        第一天他刚好吃了这些桃子的一半,又贪嘴多吃了一个;
        第二天他也刚好吃了剩余桃子的一半,贪嘴多吃了一个;
        第三天他又刚好吃了剩下的桃子的一半,并贪嘴多吃了一个。
        第四天起来一看,发现桃子只剩下一个了。
        请问小猴买了几个桃子?
'''
# 第4天还剩下1个桃子
peach = 1
for i in range(3):
    peach = peach * 2 + 1
print("总共 %d 个桃子" % peach)

'''
练习4:
    九九乘法表
'''

for x in range(9):
    for y in range(x + 1):
        print("%d * %d = %d" % (x + 1, y + 1, (x + 1) * (y + 1)), end='  ')
    print()

第六节

字典、范围、序列

在这里插入代码片`'''
字典学习:
    用来存储多个数据,通常用于存储描述一个物体的相关信息
    和列表的区别:
        列表:有序的对象集合
        字段:无序的对象集合
'''
dictionary_demo = {
    "name": "张三",
    "age": 18,
    "gender": "男",
    "language": "Eng"
}
print(dictionary_demo)

# 空的字典
dictionary_1 = {}
print(dictionary_1)

dictionary_2 = dict()
print(dictionary_2)

dictionary_3 = dict([('a', 1), ('b', 12), ('c', 14), ('d', 21)])
print(dictionary_3)

# 字典相关的方法
# 字典的修改
dictionary_3['a'] = 999
print(dictionary_3)
# 字典的遍历
for key, value in dictionary_3.items():
    print(key, value)

print("*"*20)
# 遍历value
for v in dictionary_3.values():
    print(v)
print("*"*20)
# 遍历key
for key in dictionary_3.keys():
    print(key, dictionary_3[key])

#字典的copy
print("*"*20)
dictionary_4 = dictionary_3.copy()
print(dictionary_4)

#字典的去除
dictionary_4.pop('a')
print(dictionary_4)
`

列表

'''
    列表:
        1、用 [] 定义,数据之间使用 , 分隔
        2、列表的索引从0开始
        3、索引就是数据在列表中的位置编号,索引又可以称为下标
        4,如果取值超过索引范围,程序就会报错
'''
score_1 = 60
score_2 = 90
score_3 = 87
score_4 = 55
score_5 = 72
# 平均值
average = (score_1 + score_2 + score_3 + score_4 + score_5) / 5
print("average = %.2f" % average)

list_one = (69, 11, 12, 88, 90)
print("list_one max的最大值:%d" % max(list_one))
print("list_one max的最小值:%d" % min(list_one))

print("*" * 30)

print("******************** 【列表的创建】 ************************")
# 列表的创建
# 创建一个空数组
list_two = []
print(list_two)
list_three = [69, 11, 12, 88, True, "hello", 'hi', '我是']
print(list_three)
list_four = list()
print(list_four)
list_five = ['python', 'java', 'hi', 'hello']

print("******************** 【列表相加】 ************************")
# 列表相加
print(list_three + list_five)

print("******************** 【列表相乘】 ************************")
# 列表相乘
print(list_five * 3)

print("******************** 【成员判断】 ************************")
# 成员判断
print('C#' in list_five)
print('js' not in list_five)

print("******************** 【列表遍历】 ************************")
'''
列表遍历:
    遍历就是从头遍历到尾部,执行相同的操作
'''
for param in list_five:
    print("%s" % param)
print("*" * 20)
# 枚举遍历 x:下标 y:数值
for index, param in enumerate(list_five):
    # print(index, param)
    print("索引是:%d ,数值是: %s" % (index, param))
print("*" * 20)
for x in range(len(list_five)):
    print(x, list_five[x])

print("*" * 20)
# 添加元素
print(list_five)
list_five.append("lastParam")
print(list_five)

# 将 list_five 的数据追加到列表
list_five.extend(['one', 'two', 'three', 'let go'])
print(list_five)
list_five.remove('one')
print(list_five)
# 删除索引为3的值
list_five.pop(3)
print(list_five)

# 修改索引为 0 的值
list_five[0] = 'update'
print(list_five)

# 逆序
list_five.reverse()
print(list_five)

# 二维数组
print("*" * 20)
list_sever = [
    [1, 2, 3],
    ['a', 'b', 'c'],
    [4, True, False]
]
print(list_sever)

print("*" * 20)




范围

'''
    range 学习:
        range(start,end,[step=1]),生成一个等差序列[start, end)

        注意序列属于不可变序列,不支持元素修改,不支持+和*操作。
        用途:
            range一般用于for-in循环遍历
'''
print(list(range(10)))
# 打印出基数 start:1 end:表示结束值,但是不包括 step:步长
print(list(range(1, 10, 2)))
# 打印1-10之间的数
print(list(range(1, 10)))

# 计算1-100 的和
num_count = 0
for i in range(1, 101):
    num_count += i
print(num_count)

# 计算水仙花数 : 三位数,每一位数字的立方和 = 三位数本身
# 123   1^3+2^3+3^3 = 123
# for i in range(100,1000):
for i in range(100, 1000):
    t = str(i)
    a = int(t[2])
    b = int(t[1])
    c = int(t[0])
    # print("a  %d , b = %d ,c = %d" % (a, b, c))
    if a**3 + b**3 + c**3 == i:
        print(i)


序列

'''
    序列:
        可以通过下标访问成员,这些类型称之为序列。

    函数      	描述                  	备注
    len(item)	计算容器中元素个数
    del(item)	删除变量	                del 有两种方式
    max(item)	返回容器中元素最大值	    如果是字典,只针对 key 比较
    min(item)	返回容器中元素最小值	    如果是字典,只针对 key 比较

    描述      python 表达式           结果       支持的数据类型
    切片      "0123456789"[::-2]  	"97531"	  字符串、列表、元组



    序列的通用操作
    运算符	      Python 表达式	        结果	                            描述	            支持的数据类型
    +	          ['a','c'] + ['d']	    ['a','c','d']	                合并	            字符串、列表、元组
    *	          ["hello"] * 2	        ['hello', 'hello']	            重复个数 	    字符串、列表、元组
    in	          'a' in ('a', 'b')	    True	                        元素是否存在	    字符串、列表、元组、字典
    not in	      'a' not in ('c', 'b')	True	                        元素是否不存在	字符串、列表、元组、字典
    > >= == < <=  (1, 2, 3) < (2, 2, 3)	True	                        元素比较	        字符串、列表、元组
'''

collection_a = ['a', 'b', 'c']
collection_b = ['d', 'e', 'f']
print("集合a 和 集合b的结果是:", collection_a + collection_b)

print("*" * 20)
collection_c = ['hello']
print(collection_c * 5)

# print("a in ('a' ,'b' , 'c')" % a in ('a' ,'b' , 'c') )
print('a' in ('a', 'b', 'c'))

print('cc' in ('a', 'b', 'c'))

'''
    集合比较是比较 
        collection_a > collection_b
        比较的是 字典序规则
        'a' 的 Unicode 码是 97
        'd' 的 Unicode 码点(100)
'''
print(collection_a > collection_b)




集合

'''
集合:set 去除
    特点:
        1,不允许有重复的元素
        2,一种无序的
'''
# set 的创建
set_1 = set()
print(set_1)

set_2 = {1, 1, 2, 3, 4, 6}
print(set_2)
print(type(set_2))

# 列表创建 list -> set
set_3 = set([1, 2, 3, 4, 4, 5, 3])
print(set_3)

# tuple - > set
set_4 = set((1, 12, 12, 13, 1))
print(set_4)
print(type(set_4))

# dir -> set
set_5 = set({'name': 'jon', 'age': 18, 'sex': '男'})
print(set_5)
print("******8")
print(set_5)

# 常用的方法
set_5.remove('name')
print(set_5)
set_5.add('come in')
print(set_5)

print("*"*20)
for param in set_5:
    print(param)

字符串

'''
    字符串学习
'''
str1 = "hello"
# 空串
str2 = ''
print(str2)

# 字符串的乘法
print(str1 * 3)

# 字符串的索引 :索引计数从0开始
print(str1[1])

print("*" * 20)
# 字符串的遍历
for param in str1:
    print(param)

元组

'''
    元组学习:
        Tuple(元组)与列表类似,不同之处元组的元素不能修改
        用于存储一串信息,数据之间使用,进行分隔
        元组用()定义
'''
tuple_demo = ('天气', 28, True, 66.22, 'hello', "hello")
print(tuple_demo)
print(type(tuple_demo))

tuple_demo_01 = ('洗脚',)
print(tuple_demo_01)
print(type(tuple_demo_01))

# 类型转换 会拆解出单个的字母
tuple_demo_02 = tuple('hello')
print(tuple_demo_02)

# list -> tuple
tuple_demo_03 = tuple([1, 2, 23, 5, 88, 99])
print(tuple_demo_03)
print(type(tuple_demo_03))

string_01 = str('hello hi')
print(string_01)
print(type(string_01))
print(string_01[1])

print("**************************【元组常用方法】**********************************")
a = tuple_demo.count('hello')
print(a)

# 元组遍历
for param in tuple_demo:
    print(param)

print("*" * 20)
for index, param in enumerate(tuple_demo):
    print(index, param)
print("*" * 20)
for param in range(len(tuple_demo)):
    print(param, tuple_demo[param])


案例练习

'''
作业一:
    用户登陆系统
'''
users_manage = {
    '小明': {'name': '小明', 'password': '8888', 'age': 18, 'status': True, 'email': '123@163.com'},
    '小华': {'name': '小华', 'password': '6666', 'age': 19, 'status': False, 'email': '234@163.com'},
    '小丽': {'name': '小丽', 'password': '7777', 'age': 20, 'status': True, 'email': '456@163.com'}
}

print(users_manage)
for i in range(3):
    input_name = input('请输入你的名字:')
    input_password = input("请输入你的密码:")
    if input_name in users_manage and input_password == users_manage[input_name]['password'] and users_manage[input_name]['status']:
        print("欢迎登陆xxx管理系统")
        break
    elif input_name in users_manage and not users_manage[input_name]['status']:
        print("账号状态失效,请联系管理员")
    elif input_name in users_manage and input_password != users_manage[input_name]['password']:
        print("密码输入有误请重新输入")
    else:
        print("用户不存在,请检查用户输入是否正确")

第七节

异常

'''
    异常学习:
        1,代码没有问题,可以运行,但会在运行时出现问题,比如越界异常、除以0异常
        2,出现异常,给用户的体感不好,页面渲染失败,xxx错误xxx异常
        3,python支持自己处理异常

        常见的异常类型:
            报错类型	            描述
            AssertionError	    当assert断言条件为假的时候抛出的异常。
            AttributeError  	当访问的对象属性不存在的时候抛出的异常
            IndexError	        超出对象索引的范围时抛出的异常。
            KeyError	        在字典中查找一个不存在的key抛出的异常
            NameError   	    访问一个不存在的变量时抛出的异常。
            OSError	            操作系统产生的异常。
            SyntaxError	        语法错误时会抛出此异常。
            TypeError	        类型错误,通常是不同类型之间的操作会出现此异常。
            ZeroDivisionError	进行数学运算时除数为0时会出现此异常。
'''
# 除以0异常
num = 1 / 0
print(num)

# 捕获异常
try:
    print(1 / 0)
except ZeroDivisionError:
    print("除以0异常")
except Exception:
    print("异常")



'''
    异常学习总结:
        1,用于捕获指定类型的异常是:except
        2,抛出异常的关键字是:raise
        3,关闭文件,关闭流,关闭数据库连接 :finally字句
        4,
'''



'''
try 捕获异常学习
'''
try:
    n = int(input('请输入一个数字'))
    calculated_value = 19 / n
    print('计算的结果是:%.3f' % calculated_value)
except ZeroDivisionError as e:
    print('除以0异常')
    print("错误异常是:", e)
except:
    print('请输入一个数字')
else:
    print('try except 没有捕获到异常 ,执行else模块')
finally:
    print("这里是 finally 语句模块")

raise

'''
    raise 学习
        手动抛出一个指定类型的异常,无论是哪种异常都可以带一个字符串的参数,对异常进行描述
'''
# 校验密码的长度
try:
    input_password = input('请输入你的新密码:')
    if len(input_password) < 10:
        raise ValueError('密码的长度小于10')
    else:
        print('密码校验通过')
except Exception as e:
    print('捕获的异常是:', e)

案例学习

'''
    计算器:+-*/
        简易计算器说明:
            1,仅支持+-*/运算
            2,除数不能为0
'''
while True:
    try:
        num_1 = input("请输入第一个数:")
        num_2 = input("请输入第二个数:")
        calculation_type = input("请输入计算类型提示:【当前版本仅支持+-*/版本】")
        if "+" == calculation_type:
            result = int(num_1) + int(num_2)
            print("当前执行的是加法,执行的结果是:%d" % result)
        elif "-" == calculation_type:
            result = int(num_1) - int(num_2)
            print("当前计算的结果是减法,执行的结果是:%d" % result)
        elif "*" == calculation_type:
            result = int(num_1) * int(num_2)
            print("当前计算的结果是乘法,执行的结果是:%d" % result)
        elif "/" == calculation_type:
            result = int(num_1) / int(num_2)
            print("当前计算的结果是除法,执行的结果是:%.2f" % result)
        elif "==" == calculation_type:
            print("欢迎下次使用xxx牌计算器")
            break
        else:
            print("当前计算器版本,只支持+-*/运算,不支持当前 %s 运算" % calculation_type)
    except ZeroDivisionError:
        print("除数不可以为0,请重新输入")
    except Exception as e:
        print("这里是兜底异常:%s" % e)

第八节

作用域

'''
作用域案例:
    全局变量:
        global 声明 xx为全局变量,可以修改全局变量的值
    局部变量
'''
# 全局变量
global_value = 0
# 可变的数组
global_list = [1, 2, 3, 4]


def make_correction_value():
    # global global_value 修改全局变量,函数外打印出修改全局变量外的值
    # global global_value
    global_value = 123
    global_list[2] = 77
    local_value = 86
    print("函数中的global_value ", global_value)
    print("函数中局部变量local_value  ", local_value)
    print("函数中的global_list  ", global_list)


make_correction_value()
print("调用 make_correction_value 函数后 global_value  ", global_value)
print("调用 make_correction_value 函数后 global_list ", global_list)

函数

'''
匿名函数
'''
# 匿名函数的案例
# fun = lambda a, b: a * b
# result = fun(5, 6)
# print("匿名函数计算的结果:%d", result)

# 映射,每个数平方后,再次放到list集合里面
list_01 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = map(lambda x: x ** 2, list_01)
print(list(result))

print("*" * 30)
# reduce 累积 计算列表中所有元素的乘积  => 整个过程等价于:((((1 * 2) * 3) * 4) * 5)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
from functools import reduce

result_01 = reduce(lambda x, y: x * y, a)
print(result_01)

# 匿名函数,获取列表a中,所有的奇数
'''
    python中, 
        当 x 为奇数时,x % 2 的结果是 1(在 Python 中视为 True)
        当 x 为偶数时,x % 2 的结果是 0(视为 False)
'''
result_02 = filter(lambda x: x % 2, a)
print(list(result_02))

# 过滤掉所有不为5的数据
b = [1, 2, 3, 40, 5, 6, 0, 6, 0, 5]
result_03 = filter(lambda x: x != 5, b)
print(list(result_03))

print("*" * 20)

# 假设 a = [12, 3, 456],期望的输出是 123456。 【反向遍历,将整数按照原顺序拼接出一个新的整数】
a = [12, 3, 456]
result = 0
mul = 1
for i in a[::-1]:
    result = result + i * mul
    mul = mul * 10 ** len(str(i))
    print("当前 i=%d, result=%d , mul=%d" % (i, result, mul))
print(result)
result = reduce(lambda x, y: x * 10 ** len(str(y)) + y, a)
print(result)




函数

'''
 函数学习:
    形式参数:方法题里面的参数
    实际参数:调用方法传递的参数

    可变参数
        def variable_parameter(*args):

'''


# 形式参数
def calculation_sum(num1, num2):
    return num1 + num2


# 调用方法,传入实参
result = calculation_sum(1, 2)
print(result)


# 默认的参数,缺省参数,如果num2有值,则用传入的数值,没有传则是默认的2
def default_parameters(num1, num2=2):
    return num1 * num2


result_2 = default_parameters(2)
print(result_2)

result_3 = default_parameters(2, 4)
print(result_3)


# 常用场景:录入学生信息、录入身份信息、录入酒店信息
# breakfast 1:需要早餐 0:不需要早餐
def hotel_info(name, phone, breakfast='要'):
    return "录入顾客信息,名字是%s,手机号码%s,是否要早餐:%s" % (name, phone, breakfast)


customer_one = hotel_info("jack", '153xxx', "要")
print(customer_one)

customer_two = hotel_info("rose", '156xxx', "不要")
print(customer_two)

print("**********************【可变参数】***************************")


# 可变的参数1
def variable_parameter(*args):
    print(args)
    result = 0
    for arg in args:
        result += arg
    print("计算的结果是:%d" % result)
    return result


result_three = variable_parameter(1, 2, 3, 4, 5)
print(result_three)


# 可变参数2:接收字典
def variable_dir(**kwargs):
    print(kwargs)
    for key, value in kwargs.items():
        print(key, value)


dir_param = {"name": "特伦", "price": 9.9, "sale": True}
variable_dir(**dir_param)

案例编写:

'''
    梯子走法
        10阶楼梯,每次上1个台阶或者上2个台阶,问一共有多
'''
a = [0, 1, 2]
for i in range(3, 11):
    a.append(a[i - 1] + a[i - 2])
    print("楼梯有%d阶的时候,有%d的走法" % (i, a[-1]))

'''
案例:
    名片管理系统:
'''
cards = [
    {"name": "jack", "age": 18, "phone": "123", "password": "123123", "email": "123@qq.com"},
    {"name": "rose", "age": 19, "phone": "234", "password": "234234", "email": "234@qq.com"},
    {"name": "tom", "age": 23, "phone": "345", "password": "345345", "email": "345@qq.com"},
]


# 展示菜单
def show_menu():
    print("*" * 20)
    print(''' 欢迎登陆 【名片管理系统】
            1.新建名片
            2.显示名片
            3.修改名片
            4.删除名片
            5.显示所有名片
            0.退出系统''')
    print("*" * 20)


# 新建名片
def new_card(name, age, phone, password, email):
    user = {
        "name": name,
        "age": age,
        "phone": phone,
        "password": password,
        "email": email
    }
    cards.append(user)
    return True


# 展示所有的名片
def show_all_cards():
    print("打印所有的card")
    for card in cards:
        print(card)


# 修改名片
def update_card(name, age, phone, password, email):
    for card in cards:
        if card["name"] == name and card["password"] == password:
            card["age"] = age
            card["phone"] = phone
            card["email"] = email
            return True
    else:
        return False


# 删除名片
def delete_card(name, password):
    for card in cards:
        if card["name"] == name and card["password"] == password:
            cards.remove(card)
            return True
    else:
        return False


# 退出管理系统
def curt_down_management():
    print("欢迎下次登陆")

show_menu()
while True:
    operate_input = input("请输入要操作的序列号:")
    if operate_input == "1":
        name = input("请输入你要新增的名字:")
        age = int(input("请输入你要新增的年龄:"))
        phone = int(input("请输入你要新增的手机号:"))
        password = input("请输入你要新增的密码:")
        email = input("请输入你要新增的邮箱:")
        result = new_card(name, age, phone, password, email)
        if result:
            print("新增名片成功")
            show_all_cards()
        else:
            print("新增名片失败,请重试")
    elif operate_input == "2":
        show_all_cards()
    elif operate_input == "3":
        name = input("请输入你要修改的名字:")
        age = int(input("请输入你要修改的年龄:"))
        phone = int(input("请输入你要修改的手机号:"))
        password = input("请输入你要修改的密码:")
        email = input("请输入你要修改的邮箱:")
        result = update_card(name, age, phone, password, email)
        if result:
            print("修改名片成功")
            show_all_cards()
        else:
            print("修改名片失败,请验证用户名和密码是否正确")
    elif operate_input == "4":
        name = input("请输入你要删除的名字:")
        password = input("请输入你要删除的密码:")
        result = delete_card(name, password)
        if result:
            print("删除名片成功")
            show_all_cards()
        else:
            print("删除名片失败,请检查用户名和密码是否正确")
    elif operate_input == "5":
        show_all_cards()
    elif operate_input == "0":
        curt_down_management()
        break
    else:
        print("输入菜单栏有误,请重新输入")

第九节

模块包客户端

模块

'''
模块常见标准:
模块	         用途
os       	 os 模块提供了许多与操作系统交互的函数,例如创建、移动和删除文件和目录,以及访问环境变量等。
sys	         sys 模块提供了与 Python 解释器和系统相关的功能,例如解释器的版本和路径,以及与 stdin、stdout 和 stderr 相关的信息。
time	     time 模块提供了处理时间的函数,例如获取当前时间、格式化日期和时间、计时等。
datetime	 datetime 模块提供了更高级的日期和时间处理函数,例如处理时区、计算时间差、计算日期差等。
random	     random 模块提供了生成随机数的函数,例如生成随机整数、浮点数、序列等。
math	     math 模块提供了数学函数,例如三角函数、对数函数、指数函数、常数等。
re	         re 模块提供了正则表达式处理函数,可以用于文本搜索、替换、分割等。
json    	json 模块提供了 JSON 编码和解码函数,可以将 Python 对象转换为 JSON 格式,并从 JSON 格式中解析出 Python 对象。
urllib 	    urllib 模块提供了访问网页和处理 URL 的功能,包括下载文件、发送 POST 请求、处理 cookies 等。

'''
import time

result = time.time()
print(result)

import datetime

print(datetime.time)

'''
函数名	                        函数说明
randrange(start,stop,step)	    start 指定范围的起始值 包含本身,默认是0;stop 指定范围的结束值 不包含本身; step 步长,默认步长是1。该函数返回一个整数
randint(start,end)	            返回[start end]之间的一个随机整数,start必须小于end
random()	                    返回一个[0.0,1.0)之间的随机小数
choice(seq)	                    返回一个序列(列表、元组,字符串)中返回一个随机元素
shuffle(seq)                	将序列元素随机排列(打乱顺序)
'''

import random

# 生成随机小数
print(random.random())

# 生成随机小数
list = []
for i in range(5):
    list.append(random.randrange(0, 5))
print(list)

# 获取列表中的随机元素
print(random.choice(list))
print(random.choice(list))
print(random.choice(list))
print(random.choice(list))
print(random.choice(list))

print(random.choice("jack and rose"))
print("*" * 20)

# 将序列随机打乱(打乱顺序)
list_02 = [1, 2, 3, 4, 5]
random.shuffle(list_02)
print(list_02)

# 获取集合中的随机数
list_03 = [1,2,3,4,5,6,7,8,9]
print(list_03[random.randint(0,len(list_03) - 1)])


# def random_string_length(length):
#     str = ''
#     for i in range(length):
#         str += chr(random.randint(ord("A"),ord("Z")))
#     return str
#
# # 生成一个随机字母组成列表
# result_03 = random_string_length(8)
# print(result_03)



时间

'''
时间学习
'''

import  time

# 时间戳:1970年
result_time  = time.time()
print(result_time)

# time.struct_time(tm_year=2026, tm_mon=4, tm_mday=9, tm_hour=10, tm_min=21, tm_sec=27, tm_wday=3, tm_yday=99, tm_isdst=0)
# 2026-04-09 10:21:27
local_time = time.localtime()
print(local_time)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))



函数

'''
函数名	        函数的说明	        示例
math.ceil()	    向上取整	            math.ceil(18.1) #19
math.floor()	向下取整	            math.floor(18.1) #18
math.sqrt	    求平方根            	math.sqrt(100)
'''

import math
result_01 = math.ceil(11.01)
print(result_01)

result_02 = math.floor(11.01)
print(result_02)

result_03 = math.sqrt(64)
print(result_03)


模块导入

'''
模块导入学习:
    模块:每一个扩展名 py 的结尾 python文件都是一个模块
    模块可以理解为:工具包,Java中的jar包

    import module_demo
    from module_demo import calculate_sum

'''
# 方式一:直接导入包
# import module_demo
#
# result = module_demo.calculate_sum(1,2,3,4,5)
# print(result)

# 方式二:导入包中的指定方法
# from module_demo import calculate_sum
#
# result = calculate_sum(1, 2, 3, 4, 5)
# print(result)

# 方式三:导入的方法起别名
# from module_demo import calculate_sum as calculation_sum
#
# result = calculation_sum(1, 2, 3, 4, 5)
# print(result)


# from module import card_management
#
# result = card_management.show_all_cards()
# print(result)

from module import password_tools
# 随机生成 10位的 大小写字母
result = password_tools.random_string(10)
print(result)




正则

'''
    正则学习
'''

import  re

# \d 匹配任意数字,等价于 [0-9]
result_01 = re.match(r'\d+','1234567890x1sx')
print(result_01)
result = re.match(r'\d+','1234234234')
print(result)

# \w 匹配字母数字及下划线
result_02 = re.match(r'\w+',"hello$$123_#%#")
print(result_02)

# \s 匹配任意空白字符   \S 匹配任意非空字符
result_03 = re.match(r'^\s+$',"   ")
print(result_03)

# . 匹配任意字符
result_04 = re.match(r'^code\d-\d-.+$','code1-random')
print(result_04)


# 案例配置验证手机号码
result_05 = re.match(r'^1\d{10}$','15337668696')
print(result_05)

客户端

import socket

# 创建 socket 客户端
sk = socket.socket()
# 连接服务器
sk.connect(("127.0.0.1", 9297))

while True:
    send_data = input("请输入你要发送的内容:")
    # 发送数据
    sk.send(send_data.encode("utf8"))
    # 等待响应
    accept_data = sk.recv(1024)

    print("接收到服务器发送的数据:", accept_data.decode("utf8"))



'''
    socket 客户端
'''

import socket

# 创建socket客户端
so = socket.socket()
# 设置IP和端口号
so.bind(("0.0.0.0", 9297))
# 设置监听
so.listen(5)

collection, address = so.accept()
print(collection)
print(address)

while True:
    accept_data = collection.recv(1024)
    print("收到客户端的消息是:", accept_data.decode("utf8"))
    send_data = "收到!"
    collection.send(send_data.encode("utf8"))

案例编写:
init.py

module_demo.py

'''
    卡片管理系统工具包
'''

cards = [
    {"name": "jack", "age": 18, "phone": "123", "password": "123123", "email": "123@qq.com"},
    {"name": "rose", "age": 19, "phone": "234", "password": "234234", "email": "234@qq.com"},
    {"name": "tom", "age": 23, "phone": "345", "password": "345345", "email": "345@qq.com"},
]

# 展示所有的名片
def show_all_cards():
    print("打印所有的card")
    for card in cards:
        print(card)

# 展示菜单
def show_menu():
    print("*" * 20)
    print(''' 欢迎登陆 【名片管理系统】
            1.新建名片
            2.显示名片
            3.修改名片
            4.删除名片
            5.显示所有名片
            0.退出系统''')
    print("*" * 20)


# 新建名片
def new_card(name, age, phone, password, email):
    user = {
        "name": name,
        "age": age,
        "phone": phone,
        "password": password,
        "email": email
    }
    cards.append(user)
    return True




# 修改名片
def update_card(name, age, phone, password, email):
    for card in cards:
        if card["name"] == name and card["password"] == password:
            card["age"] = age
            card["phone"] = phone
            card["email"] = email
            return True
    else:
        return False


# 删除名片
def delete_card(name, password):
    for card in cards:
        if card["name"] == name and card["password"] == password:
            cards.remove(card)
            return True
    else:
        return False


# 退出管理系统
def curt_down_management():
    print("欢迎下次登陆")


while True:
    operate_input = input("请输入要操作的序列号:")
    if operate_input == "1":
        name = input("请输入你要新增的名字:")
        age = int(input("请输入你要新增的年龄:"))
        phone = int(input("请输入你要新增的手机号:"))
        password = input("请输入你要新增的密码:")
        email = input("请输入你要新增的邮箱:")
        result = new_card(name, age, phone, password, email)
        if result:
            print("新增名片成功")
            show_all_cards()
        else:
            print("新增名片失败,请重试")
    if operate_input == "2":
        show_all_cards()
    elif operate_input == "3":
        name = input("请输入你要修改的名字:")
        age = int(input("请输入你要修改的年龄:"))
        phone = int(input("请输入你要修改的手机号:"))
        password = input("请输入你要修改的密码:")
        email = input("请输入你要修改的邮箱:")
        result = update_card(name, age, phone, password, email)
        if result:
            print("修改名片成功")
            show_all_cards()
        else:
            print("修改名片失败,请验证用户名和密码是否正确")
    elif operate_input == "4":
        name = input("请输入你要删除的名字:")
        password = input("请输入你要删除的密码:")
        result = delete_card(name, password)
        if result:
            print("删除名片成功")
            show_all_cards()
        else:
            print("删除名片失败,请检查用户名和密码是否正确")
    elif operate_input == "5":
        show_all_cards()
    elif operate_input == "0":
        curt_down_management()
        break
    else:
        print("输入菜单栏有误,请重新输入")

password_tools.py

'''
    密码工具类
'''

import random,re,time

# 随机生成字符串
def generate_char(big):
    if big:
        return chr(random.randint(ord("A"),ord("Z")))
    else:
        return chr(random.randint(ord("a"),ord("z")))

# 随机生成指定长度字符串
def random_string(length):
    str = ""
    for i in range(length):
        str += generate_char(random.choice([True,False]))
    return str

# result = random_string(10)
# print(result)

第十节

csv 文件

csv

'''
csv 语法
'''
import csv , random

from module.password_tools import *

list_score = []
def random_score(n = 100):
    subjects = ['java','C' ,'js','python']
    names = []
    for i in range(n//len(subjects)):
        name = random_string(random.randint(3,6))
        names.append(name)
    for i in range(n):
        subject = random.choice(subjects)
        score = random.randint(40,100)
        name = random.choice(names)
        for param in list_score:
            if param[0] == name and param[1] == subject:
                break
        else:
            list_score.append([name,subject,score])

def average():
    with open("data.csv",mode='r',encoding='utf-8') as read:
       cf =  csv.reader(read)
       # 表头
       header = next(cf)
       scores = []
       for i in cf:
           scores.append(int[i])
       return sum(scores)/len(scores)

def make_datas():
    with open("data.csv",mode='a' ,encoding='utf-8') as f :
        cf = csv.writer(f)
        random_score()
        cf.writerows(list_score)


make_datas()

文件

'''
文件追加
'''
write_file = open("a.txt", mode='a', encoding="utf-8")

write_file.write("追加文件\n")
write_file.write("追加文件1\n")
write_file.write("追加文件2\n")

write_file.close()


'''
    文件学习:

        文件格式:
            纯文本文件编码格式常见:ASCII、ISO-8859-1、GB2312、GBK、UTF-8、UTF-16 等
            二进制文件与文本文件的一个最主要的区别在于是否有统一的字符编码格式,二进制文件顾名思义是直接由0与1组成,
            无统一的字符编码。如图片文件(jpg、png),视频文件(avi、mp4)等。

        绝对路径|相对路径
            绝对路径:从磁盘到文件的路径
            相对路径:共同的参考位置



      mode	    解释
        r	    只读【默认模式,文件必须存在,不存在则抛出异常】
        w	    只写,写之前会清空文件的内容,如果文件不存在,会创建新文件
        a	    追加的方式,在原本内容中继续写,如果文件不存在,则会创建新文件
        r+  	可读可写
        w+	    打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
        a+	    打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
        b	    rb、wb、ab、rb+、wb+、ab+意义和上面一样,用于二进制文件操作
'''

# 读取文件步骤:  打开文件 -> 读取文件内容 -> 关闭文件

import os

# 相对路径
# a_file = open("a.txt")
# print(a_file.read())
# a_file.close()

path = os.getcwd()

full_path = path + "/a.txt"
print(full_path)

read_file = open(full_path, mode='r', encoding='utf-8')

# 读取文件 5个字符
# print(read_file.read(5))
print(read_file.readline())

# 流关闭
read_file.close()

with语法

'''
with语法
'''
with open("a.txt",mode='r',encoding='utf-8') as r:
    context = r.read()
    print(context)


'''
写入文件
    写入文件会把,原文件的内容替换掉 \n 是换行作用
'''
# write_file = open("a.txt",mode='w',encoding="utf-8")
# write_file.write("hi,")
# write_file.write("我是捷克")
# write_file.write("你是谁\n")
#
# write_file.write("你是来干啥的\n")
#
# context = ["我是捷克,来自收到就发了十几分损公肥私结果","临时决定分手是德弗里斯就发了个帅哥很帅的鬼斧神工"]
# for i in context:
#     write_file.write(i + "\n")
#
# # 流关闭
# write_file.close()

# 读取文件
read_file = open("a.txt", mode='r', encoding="utf-8")
print(read_file.read())
read_file.close()


案例编写

'''
开发一个笔记本
'''

def write_text():
    date = input("请输入记录的日期:")
    text = input("请输入日记内容:")
    file_name = "日记本.txt"
    write = open(file_name, "a", encoding="utf-8")
    write.write('split\n')
    write.write(date + "\n")
    write.write(text+'\n')
    write.close()
    return True

# 退出系统
def quit_system():
    print("退出系统, 欢迎下次使用")

# 查看日志
def read_txt(day = '-1'):
    filename = '日记本.txt'
    read = open(filename,mode='r',encoding="utf-8")
    context = read.read()
    read.close()

    if day != '-1':
        all_text = context.split("split\n")
        for text in all_text:
            if text[:10] == day:
                print(text)
                return True
        return False
    else:
        context = context.split("split\n")
        print(context)

def node_menu():
    print("*"*20)
    print('''
        欢迎登陆日记本系统
        1.编写日记
        2.查看日记
        3.退出系统
    ''')
    print("*"*20)

node_menu()
while True:
    operate = input("请输入操作类型")
    if operate == '1':
        if write_text():
            print("日记保存成功")
        else:
            print("日记保存失败")
    elif operate == '2':
        day = input("请输入你要检查的日期【-1 表示全部内容】")
        if read_txt(day):
            print("日记加载完毕")
        else:
            print("未查询到日记信息,请重试")
    elif operate == '3':
        quit_system()
    else:
        print("输入有误,请重新输入")

第十一节

类定义

'''
    类的定义
        类的实例化
            实例名 = 类() 的方式实例化对象,为类创建一个实例

'''


# 定义基类
class Student(object):
    pass


# 实力化对象
jack = Student()
print(type(jack))
# 结果是:<class '__main__.Student'>

# 验证实例 jack的 类型
print(isinstance(jack, Student))
print(isinstance(jack, object))




类方法

'''
    类方法:
        带有 @classmethod 注解的方法案例如下:
            @classmethod
            def class_function(cls):
                print("第%d保护的鱼类" % cls.count_numbers)
'''


class Fish(object):
    count_numbers = 0
    protection_level_class = ["一级", "二级", "三级", "四级"]

    def __init__(self, name, age, province, level):
        self.name = name
        self.age = age
        self.province = province
        Fish.count_numbers += 1
        if level not in Fish.protection_level_class:
            raise ValueError("保护等级错误,请重新选择")
        else:
            self.level = level

    @classmethod
    def class_function(cls):
        print("第%d保护的鱼类" % cls.count_numbers)

    # 实力化方法
    def show(self):
        print("我的名字是:%s,年龄是:%d,来自:%s,等级是:%s" % (self.name, self.age, self.province, self.level))

    def set_food(self, food):
        self.food = food

    def show_food(self):
        return self.food.show_food_desc()

    # 保护等级提高
    def protection_level_up(self):
        current_level = Fish.protection_level_class.index(self.level)
        if current_level < len(Fish.protection_level_class) - 1:
            self.level = Fish.protection_level_class[current_level + 1]

    # 保护等级降级
    def protection_level_down(self):
        current_level = Fish.protection_level_class.index(self.level)
        if current_level > 0:
            self.level = Fish.protection_level_class[current_level - 1]



cetacean = Fish("cetacean", 21, "太平洋", "一级")
print("*" * 20)
Fish.class_function()



'''
类的属性
'''
class Student(object):

    # 初始化构造函数
    def __init__(self,name,age,city):
        self.name = name
        self.age = age
        self.city = city

rose = Student("rose",18,"伦敦")
# 获取实例(对象)的所有的属性
print(rose.__dict__)


jack = Student("jack",11,"USA")
print(jack.__dict__)
# 属性值的修改
jack.age = 12
print(jack.__dict__)



'''
类属性案例2:
    实例化对象时候,校验是否在符合的范围内
'''


class Animal(object):
    # 类的属性
    job_number = 0

    # 实例属性
    def __init__(self, name, age, province):
        self.name = name
        self.age = age
        self.province = province
        Animal.job_number += 1


liHua = Animal('liHua', 1, "中国")
print(liHua.__dict__)
print("第%d个动物" % Animal.job_number)
panda = Animal('panda', 21, "台湾")
print(panda.__dict__)
print("第%d个动物" % Animal.job_number)

print("*" * 20)


class Fish(object):
    count_numbers = 0
    protection_level_class = ["一级", "二级", "三级", "四级"]

    def __init__(self, name, age, province, level):
        self.name = name
        self.age = age
        self.province = province

        Fish.count_numbers += 1
        if level not in Fish.protection_level_class:
            raise ValueError("保护等级错误,请重新选择")
        else:
            self.level = level

try:
    # cetacean = Fish("cetacean", 21, "太平洋", "五级")
    cetacean = Fish("cetacean", 21, "太平洋", "一级")
    print(cetacean.__dict__)
except ValueError as e:
    print(e)


'''
    封装案例:
'''
class Person(object):
    def __init__(self,name,age):

        # 受保护的变量
        self._name = name
        # 私有的变量
        self.__age = age

        '''把函数当做变量去使用:
            @property
            def 变量名() #获取变量
            @age.setter
            def 变量名() #修改变量
         '''
    @property
    def age(self):
        return self.__age

    # @age.setter
    # def age(self,age):
    #     self.__age = age

    @age.setter
    def age(self,age):
        if isinstance(age,int):
            self.__age = age
        else:
            raise ValueError("年龄输入不合法,只能是整数类型")

zhangSan = Person('zhangSan',21)
print(zhangSan.age)

# 修改年龄的值
# zhangSan.age = 18
# print(zhangSan.age)

zhangSan.age = "六六"
print(zhangSan.age)

继承

'''
    继承:子类继承父类属性、方法。
        1.如果子类重写父类方法,调用自己的,没有则调用父类的
'''


class Animal(object):
    # 类的属性
    job_number = 0

    # 实例属性
    def __init__(self, name, age, province):
        self.name = name
        self.age = age
        self.province = province

    def desc_animal(self):
        print("这是动物类的方法:动物的名字是" + self.name)


class Dog(Animal):

    # 子类构造器冲重写
    def __init__(self, name, age, province, sleep, food):
        self.name = name
        self.sleep = sleep
        self.food = food
        self.age = age
        self.province = province

    def desc_animal(self):
        print("这里是子类的方法:动物的名字是" + self.name)


chinese_pastoral_dog = Dog("田园犬", 1, "中国", "躺着", "骨头")
print(chinese_pastoral_dog.__dict__)
chinese_pastoral_dog.desc_animal()

多态

'''
    多态
'''
class Animal(object):
    def speak(self):
        print("动物叫了")
        pass


class Dog(Animal):
    def speak(self):
        print("汪汪")
        pass


class Cat(Animal):
    def speak(self):
        print("喵喵")
        pass

cat = Cat()
cat.speak()

dog = Dog()
dog.speak()

实例化

'''
    实例化方法:
'''


class Fish(object):
    count_numbers = 0
    protection_level_class = ["一级", "二级", "三级", "四级"]

    def __init__(self, name, age, province, level):
        self.name = name
        self.age = age
        self.province = province
        Fish.count_numbers += 1
        if level not in Fish.protection_level_class:
            raise ValueError("保护等级错误,请重新选择")
        else:
            self.level = level

    # 实力化方法
    def show(self):
        print("我的名字是:%s,年龄是:%d,来自:%s,等级是:%s" % (self.name, self.age, self.province, self.level))

    def set_food(self, food):
        self.food = food

    def show_food(self):
        return self.food.show_food_desc()

    # 保护等级提高
    def protection_level_up(self):
        current_level = Fish.protection_level_class.index(self.level)
        if current_level < len(Fish.protection_level_class) - 1:
            self.level = Fish.protection_level_class[current_level + 1]

    # 保护等级降级
    def protection_level_down(self):
        current_level = Fish.protection_level_class.index(self.level)
        if current_level > 0:
            self.level = Fish.protection_level_class[current_level - 1]


class Food(object):
    def __init__(self, name, energy):
        self.name = name
        self.energy = energy

    def show_food_desc(self):
        for k, v in self.__dict__.items():
            print(k, v)


cetacean = Fish("cetacean", 21, "太平洋", "一级")
print("*" * 20)
print(cetacean.__dict__)

# 面包食物
bread = Food("bread", 5000)
cetacean.set_food(bread)

print("*" * 20)
cetacean.show_food()


# try:
#     # cetacean = Fish("cetacean", 21, "太平洋", "五级")
#     cetacean = Fish("cetacean", 21, "太平洋", "一级")
#     print(cetacean.__dict__)
#     cetacean.show()
#     # cetacean.protection_level_up()
#     cetacean.protection_level_down()
#     cetacean.show()
# except ValueError as e:
#     print(e)

静态

'''
    静态方法: 带有 @staticmethod 注解注释的方法

'''
class Fish(object):
    count_numbers = 0
    protection_level_class = ["一级", "二级", "三级", "四级"]

    def __init__(self, name, age, province, level):
        self.name = name
        self.age = age
        self.province = province
        Fish.count_numbers += 1
        if level not in Fish.protection_level_class:
            raise ValueError("保护等级错误,请重新选择")
        else:
            self.level = level

    @classmethod
    def class_function(cls):
        print("第%d保护的鱼类" % cls.count_numbers)

    @staticmethod
    def check_level_method(level):
        if level not in Fish.protection_level_class:
            return False
        else:
            return True
    # 实力化方法
    def show(self):
        print("我的名字是:%s,年龄是:%d,来自:%s,等级是:%s" % (self.name, self.age, self.province, self.level))

    def set_food(self, food):
        self.food = food

    def show_food(self):
        return self.food.show_food_desc()

    # 保护等级提高
    def protection_level_up(self):
        current_level = Fish.protection_level_class.index(self.level)
        if current_level < len(Fish.protection_level_class) - 1:
            self.level = Fish.protection_level_class[current_level + 1]

    # 保护等级降级
    def protection_level_down(self):
        current_level = Fish.protection_level_class.index(self.level)
        if current_level > 0:
            self.level = Fish.protection_level_class[current_level - 1]


if Fish.check_level_method("六级"):
    print("等级校验通过")
else:
    print("等级校验不通过")

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐