函数定义和调用
# 函数
str = "itcast"
count = 0
for i in str:
count += 1
print(f"字符串{str}的长度是{count}")
# 为了实现整个过程的优化,可以将这类操作优化成函数
def my_len(data):
count =0
for i in data:
count += 1
print(f"字符串{data}的长度是{count}")
# 函数调用
my_len(str)
# 定义一个加法函数
def add(a,b):
res = a+b
return res
result=add(5,6)
print(result)
# 函数返回值之None类型
def sayHi():
print("hello")
var = sayHi()
print(f"返回的内容是{var},类型是{type(var)}")
# 在if判断中,None等同于False
def check_age(age):
if age >= 18:
return "SUCCESS"
else:
return None
result = check_age(16)
if not result:
print("未成年")
# 在函数内部将外部变量的值进行修改
temp = 100
def test():
global temp
temp = 200
test()
print(temp)
# 用global完成修改
# 综合案例:黑马ATM
money = 50000
name = input("请输入你的姓名:")
# 定义查询函数
def query(flag):
if flag:
print("-------查询余额-------")
print(f"{name}你好,你的余额剩余{money}元")
# 定义存款函数
def saving(num):
global money
money += num
print("-------存款---------")
print(f"{name}你好,你存款{num}成功")
query(False)
# 定义取款函数
def get_money(num):
global money
if money >= num:
money -= num
print("-------取款-------")
print(f"{name}你好,你取款{num}元成功")
else:
print(f"{name}你好,你的余额不足")
# 定义主菜单函数
def main():
print("-------主菜单-------")
print(f"{name}你好,欢迎来到黑马银行,请选择操作:")
print("查询余额\t[输入1]")
print("存款\t\t[输入2]")
print("取款\t\t[输入3]")
print("退出\t\t[输入4]")
return input("请输入你的选择:")
# 开始测试
while True:
keyword_input = main()
if keyword_input == "1":
query(True)
continue
elif keyword_input == "2":
num = int(input("存多少:"))
saving(num)
continue
elif keyword_input == "3":
num = int(input("取多少:"))
get_money(num)
continue
else:
print("程序退出")
break
列表
# 数据容器:可以容纳多个数据的数据类型
# 1.list列表
my_list = ["itcast", "itheima", "python"]
print(my_list, type(my_list))
# 列表类型不受限
my_list = ["itcast", 666, True]
# 嵌套列表
my_list = [[1,2,3], [4,5,6]]
# 通过下标取元素
print(my_list[0][0])
# -1表示最后一个元素,以此类推
print(my_list[-1])
# 列表方法
list = ["itcast","itheima","python"]
index = list.index("itcast")
print(f"itcast的索引值是{index}")
# 修改列表元素
list[index] = "itheima"
# 插入元素:指定位置
list.insert(1,"java")
# 追加元素:只能在最后插入
list.append("C++")
# 追加一批元素
list2 = ["C", "spring"]
list.extend(list2)
# 删除元素
# 指定下标删除
del list[2]
# 或者,这样还可以得到删除的元素
element = list.pop(2)
# 通过元素值移除,从前向后搜索
list.remove("itcast")
# 统计列表中某元素的值
num = list.count("itcast")
# 统计列表元素个数
length = len(list)
# 清空列表
list.clear()
# 列表的遍历
list = ["itcast","itheima","python"]
index = 0
while index < len(list):
element = list[index]
print(f"{element}")
index += 1
for element in list:
print(f"{element}")
元组
# 2.元组:一经定义,无法修改
t = (1, "hello", True)
# 单个元素的元组必须加逗号,否则会被识别为该单个元素的类型
t1 = ("world", )
t2 = ((1, "hello", True), (1, "world", True))
# 元组除了不能修改外,其余操作和list类似
t3 = (1, "itcast", ["itheima", "keli"])
t3[2][1] = "it黑马"
# 元组内部的list可修改
字符串
# 字符串:字符的容器,无法修改
my_str = "itheima and itcast"
value = my_str[-1]
print(value)
# 查询小字符串在整个字符串里的索引
start = my_str.index("and")
print(start)
# 字符串的替换
new_str = my_str.replace("and", "or")
print(new_str)
# 字符串分割,得到一个列表对象
my_list = my_str.split(" ")
print(my_list)
# 去空格
new_str = my_str.strip()
print(new_str)
# 去特定字符串
new_str = my_str.strip("it")
print(new_str)
# 注意所有的i和t都被去掉了
# 统计次数和求长度和元组及列表类似
# 案例测试
my_str = "itheima and itcast"
num = my_str.count("it")
print(f"有{num}个it字符")
new_str = my_str.replace(" ", "|")
print(new_str)
my_list = new_str.split("|")
print(my_list)
# 列表,元组和字符串都属于序列
# 序列的切片操作 [起始下标:结束下标:步长] 步长默认是1 起始和结束不写表示从头到尾
list = [0,1,2,3,4,5,6]
res = list[1:4]
print(res)
res2 = list[::-1]
print(res2)
# 这中操作等同于将序列反转
# 练习案例
str = "哈哈哈哈,员序程马黑来,学python"
res = str[::-1][9:14]
print(res)
# 另一种方法
res = str.split(",")[1].replace("来", "")[::-1]
print(res)
集合
# 定义集合
my_set = {"高等数学", "线性代数", "概率统计", "数据结构", "组成原理", "操作系统", "计算机网络"}
# 定义空集合
set_empty = set()
print(my_set)
print(set_empty)
# 注意:集合是无序的,不支持下标索引访问,但是允许修改,且会进行自动去重
# 添加
my_set.add("阅读理解")
# 移除
my_set.remove("阅读理解")
# 随机取元素并删除
element = my_set.pop()
print(element)
print(my_set)
# 取集合之间的差集
my_set2 = {"高等数学", "线性代数", "概率统计", "数据结构", "组成原理", "操作系统", "计算机网络"}
new_set = my_set2.difference(my_set)
print(new_set)
# 消除差集
my_set2.difference_update(my_set)
print(my_set2)
# 合并集合
my_set3 = my_set.union(my_set2)
# 统计元素个数
num = len(my_set3)
# 遍历集合: 不能用while,因为不支持下标索引
for element in my_set3:
print(element)
# 清空集合
my_set.clear()
字典
# 字典: 存储键值对
my_dict = {"张宇": 1000, "李林": 880, "李永乐": 660, "汤家凤": 1800}
# 空字典
dict_empty = {}
dict_empty2 = dict()
# 字典不可重复,如果有重复key的字典,会保留最后面的重复key元素
# 通过key访问value
num = my_dict["张宇"]
# 字典的嵌套
my_dict2 = {
"张宇": {
"基础": 300,
"强化": 1000,
"冲刺": 8+4
}, "李林": {
"基础": 880,
"强化": 108,
"冲刺": 6+4
}, "李永乐": {
"基础": 660,
"强化": 330,
"冲刺": 6+3
}, "汤家凤": {
"基础": 1800,
"强化": 180,
"冲刺": 5+8
}
}
print(my_dict2)
res = my_dict2["李林"]["基础"]
print(res)
# 新增元素
my_dict["李艳芳"] = 900
# 更新
my_dict["张宇"] = 30
# 删除
val = my_dict.pop("李艳芳")
# 获取全部key
keys = my_dict.keys()
# 遍历
for key in keys:
print(f"{key}: {my_dict[key]}")
# 或者
for key in my_dict:
print(f"{key}: {my_dict[key]}")
# 统计数量
num = len(my_dict)
# 清空
my_dict.clear()
# 案例练习
score_dict = {
"数学": {
"高等数学": 86,
"线性代数": 32,
"概率统计": 32
},
"408": {
"数据结构": 45,
"组成原理": 45,
"操作系统": 35,
"计算机网络": 25
},
"英语": {
"阅读理解": 40,
"写作表达": 30,
"小三门": 30
},
"政治": {
"选择题": 50,
"大题": 50
}
}
for element in score_dict:
for subject in score_dict[element]:
if score_dict[element][subject] >= 40:
print(score_dict[element][subject])
通用操作
# 数据容器通用操作, 以列表为例
list = [1,2,3,4,5,6,7,8,9]
# 求数量
num = len(list)
# 求最值
max = max(list)
min = min(list)
# 容器转换: 以转元组为例,其余类似,除了字典
tuple(list)
# 注意字典转其他容器会丢失value
# 排序: 无论是什么容器,排序后都会转换成列表
sorted(list)
# 反转排序
sorted(list, reverse=True)