目录
# print("hello")
# money = 50
# print("money",money)
# 字符串拼接 站位拼接 占位符用 %s % 多个字符站位用() %f是换成浮点类型的 %.2f是保留两位小数
# name = "阿巴阿巴"
# age = 18
# name_contact = "我是:%s,我的年龄是:%.2f" % (name,age)
# print("name_contact",name_contact)
# 字符串格式化快速写法
# 通过语法 : f"内容{变量}"的格式来快速格式化 快速格式化 不做精度控制,原样输出
# print(f"我叫{name},我今年{age}了")
# 练习 股价计算
name = " 传智播客 "
stock_price = 19.99 # 每股价格
stock_code = 1102254 # 股票代码
stock_price_dailt_growth_factor = 1.2 # 股票增长系数
growth_days = 7
message = "公司:%s,股票代码:%d,当前股价:%.2f,每日增长系数:%.2f,增长天数:%d" % (name,stock_code,stock_price,stock_price_dailt_growth_factor,growth_days )
message2 = "经过七天的增长之后股价达到了:%.2f" % (stock_price * stock_price_dailt_growth_factor ** growth_days)
print("message",message,message2)
# input 函数 输入函数
# print("请告诉我你是谁")
# name = input()
# print(f'我是:{name}')
# input 输出的东西都是string类型的 输入的数字也是字符串形式
# age = int(input('请输入您的年龄'))
# if age >= 18:
# print("成年")
# else:
# print("还未成年")
# elif == else if
# if age >= 18:
# print("成年")
# elif age >= 16:
# print("半成年")
# else:
# print("未成年")
# 随机数字
# import random
# num = random.randint(1,100)
# print(num)
# while循环
# sum = 0
# i = 1
# while i<=100:
# sum += i
# i+=1
#
# print(f"i={i},sum={sum}")
# 乘法表
# i = 1
# while i<10:
# j = 1
# while j<=i:
# print(f"{i} * {j} = {i*j}\t",end=" ")
# j+=1
# i += 1
# print()
# while j<=i:
# print(f"{i} × {j} = { i*j }",end=" ")
# j+=1
# i+=1
# range语句 range(5) 取得的数据 [0,1,2,3,4]
# 语法2 range(num1,num2) range(2,5) 取得的数据[2,3,4] 不包含num2本身
# 语法3 range(num1,num2,step) 获得一个从num1开始到num2 步长为2的序列
# continue 循环中中断语句 同一层continue后面的代码不执行了
# 遇到break 跳出整个循环
# for i in range(10):
# print(f'{i}')
# continue
# print("hhh")
import random
allPrice = 10000
i = 0
count = 0
for i in range(1,21):
grade = random.randint(1,10)
if grade < 5:
print(f"员工{i}的绩效分是{grade},不发工资")
continue
elif allPrice <= 0:
print("没钱了,不发了")
break
else:
count += 1
allPrice = allPrice - 1000
print(f"员工{i}发放工资1000元,当前剩余工资{allPrice}")
print(f"剩余工资为{allPrice},共发人数:{count}人")
字符串方法
'''
# 字符串高级
获取长度:len
查找长度:find 查找指定内容在字符串当中是够存在,如果存在就返回该内容在字符串中第一次出现
的开始的索引值,如果不存在,则返回-1
判断 startswitch,endswitch 判断字符串是不是以谁谁谁开头/结尾 返回true/false
count 计算出现的次数 字符串中出现某字符
replace 替换
split 切割 然后切割之后变成数组
upper 将小写字符全部变成大写字符
lower 大写变小写
strip 去空格
join 字符串拼接 一个一个加入 - 没啥用
'''
s = 'china'
print(len(s))
print(s.find('i')) # 所得索引值为2 开始下表的索引值
print(s.startswith('c'))
s1 = 'aaaaabb'
print(s1.replace('a','c'))
print(s1.upper()) # 小写变大写
s2 = 'CHINA'
print(s2.lower())
'''
列表
append 在列表的末尾添加元素
insert 在指定位置插入元素
extend 合并两个列表
'''
s1 = ['zhangsan','lisi','zhaoliu']
food_list = ['铁锅炖大鹅','酸菜五花肉']
food_list.append('小鸡炖蘑菇') # 在列表的最后添加
print(food_list)
# insert 在指定位置插入
# insert(index,object) 中index的值 就是你想插入数据的那个下标
food_list.insert(1,'巴拉巴拉')
print(food_list)
# extend 拼接两个列表
# 列表的一系列操作
#
# myList = ["itcase",'itHeiam','python']
# # 查找某元素在列表内的下表索引
# # index = myList.index('itcase')
# # # 插入元素 insert(下标,元素) insert可以指定位置
# # myList.insert(1,'ceshi')
# # # 添加到元素的尾部 append(元素)
#
# # 追加元素2:
# # 语法 列表.extend(其他元素),将其他元素取出、以此添加到列表的尾部
# testList = [1,2,3]
# myList.extend(testList)
#
# # 删除元素 del列表[下标]
# # 列表.pop(下标
#
# # del myList[2]
#
# myList.pop(2)
# # pop这个方法 是把当前的项删除后并返回当前删除的元素
# print('myList',myList)
#
# # 删除找到的第一个元素 remove('itheima')
# # 清空所有元素 clear() 不需要传递值
#
# # 统计某元素在列表中的数量 count(统计的元素)
# number = myList.count(1)
# print("当前的元素个数有",number)
#
# # 查看list中元素的数量 len(列表名称)
# print(len(myList))
# 列表练习
# 1、定义这个列表 并且用变量接收
testList = [21,25,21,23,22,20]
print("1",testList)
# 2 追加一个数字31 到列表的尾部 append()
testList.append(31)
print("2",testList)
# 追加一个新列表[29,33,30] 到列表的尾部 extend()
newList = [39,33,30]
testList.extend(newList)
print("3",testList)
# 取出第一个元素 pop()
firstLetter = testList.pop(0)
print("4",firstLetter)
# 取出最后一个元素 pop()
lasterLetter = testList.pop(len(testList)-1)
print("5",lasterLetter)
# 查找元素31 在列表中的下标位置 index
# testList.index(31)
print("6",testList.index(31))
# 列表的遍历 while for
def for_function():
for i in testList:
print("i",i)
for_function()
# for循环取出偶数
overList = []
def handlerover():
for i in range(1,11):
if i % 2 == 0:
overList.append(i)
print("overList",overList)
handlerover()
# --------------------- 元组 -----------------------
# 列表可以被修改 但是元组 一旦定义完成不能被修改 是一个只读的List 元组用()来定义 用,隔开
""" 元组当中
有index() 查找某个数据,如果数据存在则返回它所对应的下标,否则报错
count(“黑马程序员”) 统计-某个数据-在当前元组中出现的次数
len() 统计元组中元素的个数
---------元组不可以被修改-----------
但是能改元组中list 的内容 例如 ('周杰棍',11,['football','music']) 可以修改[]里面list的内容
"""
# ------------------------ 字符串 ---------------------------
# 字符串 也是只读的 不允许进行修改操作
my_chart = "itcase and itheima"
# 查找特定字符串的下标索引值 index()
print("my_chart.index()",my_chart.index("and"))
# 字符串的替换 replace(字符串1,字符串2) 将字符串内的全部:字符串1 替换成字符串2
# 替换完之后不是修改的字符串本身,而是得到了一个新的字符串
chart_List = my_chart.replace('it','程序')
print(chart_List)
# split() 函数 用来切分字符串
# strip()函数 如果不传递函数 则去除字符串收尾空格
# new_List = (" itheima aaa study ")
# print(new_List.strip())
# 如果里面有参数的话strip(12) 这个代表去除字符串里面的1 和 2
ne = new_List = (" 1222itheima a33a12a2 stu22dy ")
print("传递参数后的strip",ne.strip("2")) # 没变
# 字符串测试
str_List = ("itheima itconst boxcue")
# 统计字符串中有多少it
print(str_List.count("it"))
# 将字符串的空格,全部替换成 |
print(str_List.replace(" ","|"))
# 按照| 分割字符串
print(str_List.replace(" ","|").split("|"))
# 步长切片操作 语法:序列[起始下标:结束下标:步长]
test2_lest = [0,1,2,3,4,5]
print(test2_lest[0:4:2])
创建类 构造方法等
# 设计一个类
# class Student:
# name = None # 记录学生姓名
# gender = None # 记录学生性别
# age = None # 记录学生年龄
#
# # 创建一个对象
# stu_1 = Student()
# stu_1.name = "张三"
# stu_1.gender = "男"
# stu_1.age = 18
#
# print(stu_1.name)
# class Student:
# name = None # 记录学生姓名
# gender = None # 记录学生性别
# age = None # 记录学生年龄
# def say_name(self):
# print(f'大家好呀,我叫{self.name}') # 如果现在成员方法中访问成员变量就要加上一个self.xxx
# def say_hello(self,msg):
# print(f'大家好呀,我叫{self.name},{msg}') # 外部访问的就直接用就行了
#
# stu = Student()
# stu.name = "张三"
# stu.say_name()
#
# stu2 = Student()
# stu2.name = "李四"
# stu2.say_hello("哎呦呦")
# 设计一个闹钟类
# class Clock:
# id = None
# price = None
#
# def ring(self):
# import winsound # winsound window内置的一个方法 可以发出声
# winsound.Beep(1000,2000)
#
# # 创建出闹钟对象
#
# clock1 = Clock()
# clock1.id = 1
# clock1.price = 1000
# print(f"闹钟id是{clock1.id},闹钟的价格是{clock1.price}")
# clock1.ring()
#
# # 构造方法
# # 构造方法的名称__init__
# 在创建类对象(构造类)的时候,会自动执行
# class Student:
# age = None
# gender = None
# name = None
# 需要提供self 只要在方法中访问类的成员变量都需要self
# def __init__(self,name,age,gender):
# self.name = name
# self.age = age
# self.gender = gender
# print("Student类创建了一个类对象")
#
# stud1 = Student("张三","18","男")
# print(stud1.name)
# print(stud1.age)
# print(stud1.gender)
# 测试 学生录入
# class Student:
# name = None
# age = None
# address = None
# def __init__(self,name,age,address,index):
# self.name = name
# self.age = age
# self.address = address
# print(f"学生{index}录入信息完成,信息为:【学生姓名:{self.name},年龄{self.age},地址:{self.address}】")
# # 信息录入
# i = 0
# while True:
# i+=1
# stu_name = input("请录入学生名称:")
# stu_age = input("请录入学生年龄:")
# stu_address = input("请录入学生地址:")
# Student(stu_name, stu_age, stu_address,i)
# if i == 10:
# break
"""
其他的内置方法 __str__ 字符床方法 __eq__方法
"""
class Teacher:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return f"老师姓名:{self.name},年龄:{self.age}"
# __lt__ 魔术方法 用来比较大小的 小于 大于 __le__ 比较小于等于 和 大于等于 __eq__ 等于比较
def __lt__(self,other):
return self.age < other.age
# tea = Teacher("张三",31)
# # 这样会直接输出一个内存地址 如果写了__str__ 就会输出你所写的东西
# print(tea)
# print(str(tea))
"""
写上了__str__ 方法 就会输出str方法里面的东西
def __str__(self):
return f"老师姓名:{self.name},年龄:{self.age}"
"""
tea1 = Teacher("张三",31)
tea2 = Teacher("张四",36)
print(tea1 < tea2)
python 面向对象编程 封装 - 继承 - 多态
"""
面向对象编程 就是去创建实体类(对象)
定义私有的成员变量和成员方法 只需要在前面加两个下划线就行了 __currentxxxxx = None 私有成员变量
def __keep_singxxx(): 私有成员方法
私有方法 无法直接被类对象使用
私有变量无法赋值,也无法获取值
私有的成员是给内部去自己使用的
私有的成员变量和成员方法只能让内部的成员方法去使用 外部不能调用
封装:
"""
# class Phone:
# __current_voltage = 1# 当前的手机运行电压
# def __keep_single_core(self):
# print("让CPU以单核模式运行")
#
# def call_by_5g(self):
# if self.__current_voltage > 5:
# print("5g通话已开启")
# else:
# self.__keep_single_core()
# print("电量不足")
#
# ph = Phone()
# ph.call_by_5g()
# 私有属性 方法练习
# class Phone:
# __is_5g_enable = False
# def __check_5g(self):
# if self.__is_5g_enable:
# print("5g通话已开启")
# else:
# print("5g通话关闭,使用4g网络")
# def call_by_5g(self):
# self.__check_5g()
# ph = Phone()
# ph.call_by_5g()
"""
继承:
把已经有的功能拿过来接着用
class Phone:
IMEI = None
producer = None
def call_by_4g(self):
print("4g通话")
class Phone2022(Phone): # 写一个()就是继承 继承了Phone 类里面的所有变量和方法
face_id = None #面部识别
def call_by_5g(self):
print("5g通话")
# 继承分单继承和多继承 上述代码为单继承 多继承如下代码所示
class test(xxx,sss,aaa):
这样test类就继承了三个父类里面的所有的变量和方法了
"""
# 写一个多继承
# class NFCfunction:
# NFC_type = None
# producer = 'HM'
#
# def read_card(self):
# print("read")
#
# class RemoteControl:
# rc_type = "红外遥控"
#
# def control(self):
# print("红外遥控")
#
# class MyPhone(Phone,NFCfunction,RemoteControl):
# pass
# 如果你的类继承了很多类 已经有很多功能了,不想再写新的语法了 那就写一个pass 补全语法 后面就不用写了 函数里面也可以用
"""
如果继承了父类里面的属性和方法不满意的话 可以对父类里面的属性和方法进行复写
"""
class test1:
producer = "ITCASTProdu"
def call_by_5g(self):
print("5g通话---父类")
class test2(test1):
producer = "ITHEIMA"
def call_by_5g(self):
print("5g通话1111")
# super().call_by_5g()
test1.call_by_5g(self)
test = test2()
test.call_by_5g()
# 复写之后 如果还想用父类里面的方法或者是属性 可以用一下几个方法
# 方法一 super().xxx
# 方法二 父类名称.xxx(self) 用第二种方法的时候 一定要加self
文件操作
# 文件操作
'''
open() 函数 可以打开一个已经存在或者是创建一个新文件
open(文件路径,访问模式)
模式种类:
w:可写 每次覆盖当前文件中的数据
r:可读
a:追加
'''
# 先创建一个文件 如果已存在就 执行打开操作
# f = open('test.txt','w')
# f.write('hello world\n'*5)
# f.close()
# 读数据 read() 这样就是全部都能读到
# read 默认情况下 是一字节一字节的读 效率比较低
# 提升效率 一行一行读
f = open('test.txt','r')
# content = f.readline() # 只能读取一行
# print(content)
# f.close()
# 读取多行 readlines
# readlines 可以按照行来读取,但是会将所有的数据都读取到,并且以一个列表的形式返回
contet = f.readlines()
print(contet)
序列化
# 序列化的两种方式
# dumps() dump()
f = open('test.txt','w')
name_list = ['zhangsan','lisi','wangwu']
# 导入json模块到该文件中
import json
# 序列化
# 将python对象 变成 json字符串
names = json.dumps(name_list)
print(names)
f.write(names)
f.close()
# dump的作用就是简写了 emmm 没啥大用 记住一个就行
反序列化
# 反序列化
# 将json的字符串转变成一个python对象
f = open('test.txt','r')
content = f.read()
print(type(content))
# 反序列化的两种方式 loads load 将json字符串转变成对象的两种方式
import json
# 将json对象转变成python对象
result = json.loads(content)
print(type(result))
# 用load的话就直接读文件就行了
import json
f = open('test.txt','r')
result = json.load(f)
print(result)