提交 c92e6338 编写于 作者: 檀越@新空间's avatar 檀越@新空间 🐭

fix:加入黑马学习资料

上级 d3859db6
# 单行注释
"""
多行注释
文档注释
"""
\ No newline at end of file
"""
知识点:变量
变量的定义格式: 变量名 = 变量值
"""
# 定义一个变量:钱包, 用来存储余额数字
money = 5
# 查看一下,钱包还剩余多少钱
print(money)
666
13.14
"黑马程序员"
print(666)
print(13.14)
print("黑马程序员")
\ No newline at end of file
name = """
多行注释
"""
print(name)
# 写一个整数字面量
666
# 写一个浮点数字面量
13.14
# 写一个字符串字面量
"黑马程序员"
# 通过print语句输出各类字面量
print(666)
print(13.14)
print("黑马程序员")
# 单行注释
#
#
"""多行注释"""
"""
演示Python中变量的相关操作
"""
# 定义一个变量,用来记录钱包余额
money = 50
# 通过print语句,输出变量记录的内容
print("钱包还有:", money)
# 买了一个冰淇淋,花费10元
money = money - 20
print("买了冰淇淋花费10元,还剩余:", money, "元")
# 假设,每隔一小时,输出一下钱包的余额
print("现在是下午1点,钱包余额剩余:", money)
print("现在是下午2点,钱包余额剩余:", money)
print("现在是下午3点,钱包余额剩余:", money)
print("现在是下午4点,钱包余额剩余:", money)
Name = "张三"
Age = 11
name = "张三"
age = 11
# 方式1: 使用print直接输出类型信息
print(type("黑马程序员"))
print(type(666))
print(type(11.345))
# 方式2: 使用变量存储type()语句的结果
string_type = type("黑马程序员")
int_type = type(666)
float_type = type(11.345)
print(string_type)
print(int_type)
print(float_type)
# 方式3: 使用type()语句,查看变量中存储的数据类型信息
name = "黑马程序员"
name_type = type(name)
print(name_type)
# 将数字类型转换成字符串
num_str = str(11)
print(type(num_str), num_str)
float_str = str(11.345)
print(type(float_str), float_str)
# 将字符串转换成数字
num = int("11")
print(type(num), num)
num2 = float("11.345")
print(type(num2), num2)
# 错误示例,想要将字符串转换成数字,必须要求字符串内的内容都是数字
# num3 = int("黑马程序员")
# print(type(num3), num3)
# 整数转浮点数
float_num = float(11)
print(type(float_num), float_num)
# 浮点数转整数
int_num = int(11.345)
print(type(int_num), int_num)
# 规则1:内容限定,限定只能使用:中文、英文、数字、下划线,注意:不能以数字开头
# 错误的代码示范:1_name = "张三"
# 错误的代码示范:name_! = "张三"
name_ = "张三"
_name = "张三"
name_1 = "张三"
# 规则2:大小写敏感
Itheima = "黑马程序员"
itheima = 666
print(Itheima)
print(itheima)
# 规则3:不可使用关键字
# 错误的示例,使用了关键字:class = 1
# 错误的示例,使用了关键字:def = 1
Class = 1
# 字符串字面量之间的拼接
print("学IT来黑马" + "月薪过万")
# 字符串字面量和字符串变量的拼接
name = "黑马程序员"
address = "建材城东路9号院"
tel = 4006189090
# 不报错
print("我是:" + name + ",我的地址是:" + address + ",我的电话是:" + str(tel))
# 报错
print("我是:" + name + ",我的地址是:" + address + ",我的电话是:" + tel)
# 通过占位的形式,完成拼接
name = "黑马程序员"
message = "学IT来:%s" % name
print(message)
# 通过占位的形式,完成数字和字符串的拼接
class_num = 57
avg_salary = 16781
message = "Python大数据学科,北京%s期,毕业平均工资:%s" % (class_num, avg_salary)
print(message)
name = "传智播客"
setup_year = 2006
stock_price = 19.99
message = "%s,成立于:%d,我今天的股价是:%f" % (name, setup_year, stock_price)
print(message)
num1 = 11
num2 = 11.345
print("数字11宽度限制5,结果是:%5d" % num1)
print("数字11宽度限制1,结果是:%1d" % num1)
print("数字11.345宽度限制7,小数精度2,结果是:%7.2f" % num2)
print("数字11.345不限制,小数精度2,结果是:%.2f" % num2)
"""
演示布尔类型的定义
以及比较运算符的应用
"""
# 定义变量存储布尔类型的数据
bool_1 = True
bool_2 = False
print(f"bool_1变量的内容是:{bool_1}, 类型是:{type(bool_1)}")
print(f"bool_2变量的内容是:{bool_2}, 类型是:{type(bool_2)}")
# 比较运算符的使用
# == , !=, >, <, >=, <=
# 演示进行内容的相等比较
num1 = 10
num2 = 10
print(f"10 == 10的结果是:{num1 == num2}")
num1 = 10
num2 = 15
print(f"10 != 15的结果是:{num1 != num2}")
name1 = "itcast"
name2 = "itheima"
print(f"itcast == itheima 结果是:{name1 == name2}")
# 演示大于小于,大于等于小于等于的比较运算
num1 = 10
num2 = 5
print(f"10 > 5结果是:{num1 > num2}")
print(f"10 < 5的结果是:{num1 < num2}")
num1 = 10
num2 = 11
print(f"10 >= 11的结果是:{num1 >= num2}")
print(f"10 <= 11的结果是:{num1 <= num2}")
"""
演示练习题:成年人判断
"""
# 获取键盘输入
age = int(input("请输入你的年龄:"))
# 通过if判断是否是成年人
if age >= 18:
print("您已成年,游玩需要买票,10元.")
print("祝您游玩愉快")
"""
演示Python判断语句:if语句的基本格式应用
"""
age = 10
if age >= 18:
print("我已经成年了")
print("即将步入大学生活")
print("时间过的真快呀")
"""
演示if else练习题:我要买票吗
"""
# 定义键盘输入获取身高数据
height = int(input("请输入你的身高(cm):"))
# 通过if进行判断
if height > 120:
print("您的身高超出120CM,需要买票,10元。")
else:
print("您的身高低于120CM,可以免费游玩。")
print("祝您游玩愉快")
"""
演示Python中
if else的组合判断语句
"""
age = int(input("请输入你的年龄:"))
if age >= 18:
print("您已成年,需要买票10元。")
else:
print("您未成年,可以免费游玩。")
"""
演示if elif else练习题:猜猜心里数字
"""
# 定义一个变量数字
num = 5
# 通过键盘输入获取猜想的数字,通过多次if 和 elif的组合进行猜想比较
if int(input("请猜一个数字:")) == num:
print("恭喜第一次就猜对了呢")
elif int(input("猜错了,再猜一次:")) == num:
print("猜对了")
elif int(input("猜错了,再猜一次:")) == num:
print("恭喜,最后一次机会,你猜对了")
else:
print("Sorry 猜错了")
"""
演示if elif else 多条件判断语句的使用
"""
# 通过if判断,可以使用多条件判断的语法
# 第一个条件就是if
if int(input("请输入你的身高(cm):")) < 120:
print("身高小于120cm,可以免费。")
elif int(input("请输入你的VIP等级(1-5):")) > 3:
print("vip级别大于3,可以免费。")
elif int(input("请告诉我今天几号:")) == 1:
print("今天是1号免费日,可以免费")
else:
print("不好意思,条件都不满足,需要买票10元。")
"""
演示判断语句的嵌套使用
"""
# if int(input("你的身高是多少:")) > 120:
# print("身高超出限制,不可以免费")
# print("但是,如果vip级别大于3,可以免费")
#
# if int(input("你的vip级别是多少:")) > 3:
# print("恭喜你,vip级别达标,可以免费")
# else:
# print("Sorry 你需要买票10元")
# else:
# print("欢迎小朋友,免费游玩。")
age = 11
year = 1
level = 1
if age >= 18:
print("你是成年人")
if age < 30:
print("你的年龄达标了")
if year > 2:
print("恭喜你,年龄和入职时间都达标,可以领取礼物")
elif level > 3:
print("恭喜你,年龄和级别达标,可以领取礼物")
else:
print("不好意思,尽管年龄达标,但是入职时间和级别都不达标。")
else:
print("不好意思,年龄太大了")
else:
print("不好意思,小朋友不可以领取。")
"""
演示判断语句的实战案例:终极猜数字
"""
# 1. 构建一个随机的数字变量
import random
num = random.randint(1, 10)
guess_num = int(input("输入你要猜测的数字:"))
# 2. 通过if判断语句进行数字的猜测
if guess_num == num:
print("恭喜,第一次就猜中了")
else:
if guess_num > num:
print("你猜测的数字大了")
else:
print("你猜测的数字小了")
guess_num = int(input("再次输入你要猜测的数字:"))
if guess_num == num:
print("恭喜,第二次猜中了")
else:
if guess_num > num:
print("你猜测的数字大了")
else:
print("你猜测的数字小了")
guess_num = int(input("第三次输入你要猜测的数字:"))
if guess_num == num:
print("第三次猜中了")
else:
print("三次机会用完了,没有猜中。")
"""
演示while循环基础练习题:求1-100的和
"""
sum = 0
i = 1
while i <= 100:
sum += i
print(i)
i += 1
print(f"1-100累加的和是:{sum}")
"""
演示while循环的基础应用
"""
i = 0
while i < 100:
print("小美,我喜欢你")
i += 1
"""
演示while循环的基础案例 - 猜数字
"""
# 获取范围在1-100的随机数字
import random
num = random.randint(1, 100)
# 定义一个变量,记录总共猜测了多少次
count = 0
# 通过一个布尔类型的变量,做循环是否继续的标记
flag = True
while flag:
guess_num = int(input("请输入你猜测的数字:"))
count += 1
if guess_num == num:
print("猜中了")
# 设置为False就是终止循环的条件
flag = False
else:
if guess_num > num:
print("你猜的大了")
else:
print("你猜的小了")
print(f"你总共猜测了{count}次")
"""
演示while循环的嵌套使用
"""
# 外层:表白100天的控制
# 内层:每天的表白都送10只玫瑰花的控制
i = 1
while i <= 100:
print(f"今天是第{i}天,准备表白.....")
# 内层循环的控制变量
j = 1
while j <= 10:
print(f"送给小美第{j}只玫瑰花")
j += 1
print("小美,我喜欢你")
i += 1
print(f"坚持到第{i - 1}天,表白成功")
"""
演示使用while的嵌套循环
打印输出九九乘法表
"""
# 定义外层循环的控制变量
i = 1
while i <= 9:
# 定义内层循环的控制变量
j = 1
while j <= i:
# 内层循环的print语句,不要换行,通过\t制表符进行对齐
print(f"{j} * {i} = {j * i}\t", end='')
j += 1
i += 1
print() # print空内容,就是输出一个换行
"""
演示for循环的练习题:数一数有几个a
"""
# 统计如下字符串中,有多少个字母a
name = "itheima is a brand of itcast"
# 定义一个变量,用来统计有多少个a
count = 0
# for 循环统计
# for 临时变量 in 被统计的数据:
for x in name:
if x == "a":
count += 1
print(f"被统计的字符串中有{count}个a")
"""
演示for循环的基础语法
"""
name = "itheima"
for x in name:
# 将name的内容,挨个取出赋予x临时变量
# 就可以在循环体内对x进行处理
print(x)
"""
演示Python中的range()语句的基本使用
"""
# range语法1 range(num)
# for x in range(10):
# print(x)
# range 语法2 range(num1, num2)
# for x in range(5, 10):
# # 从5开始,到10结束(不包含10本身)的一个数字序列,数字之间间隔是1
# print(x)
# range 语法3 range(num1, num2, step)
# for x in range(5, 10, 2):
# # 从5开始,到10结束(不包含10本身)的一个数字序列,数字之间的间隔是2
# print(x)
for x in range(10):
print("送玫瑰花")
"""
演示Python for循环临时变量的作用域
"""
i = 0
for i in range(5):
print(i)
print(i)
"""
演示for循环打印九九乘法表
"""
# 通过外层循环控制行数
for i in range(1, 10):
# 通过内层循环控制每一行的数据
for j in range(1, i + 1):
# 在内层循环中输出每一行的内容
print(f"{j} * {i} = {j * i}\t", end='')
# 外层循环可以通过print输出一个回车符
print()
"""
演示嵌套应用for循环
"""
# 坚持表白100天,每天都送10朵花
# range
i = 0
for i in range(1, 101):
print(f"今天是向小美表白的第{i}天,加油坚持。")
# 写内层的循环了
for j in range(1, 11):
print(f"给小美送的第{j}朵玫瑰花")
print("小美我喜欢你")
print(f"第{i}天,表白成功")
"""
演示循环语句的中断控制:break和continue
"""
import random
num = random.randint(1, 10)
# 演示循环中断语句 continue
# for i in range(1, 6):
# print("语句1")
# continue
# print("语句2")
# 演示continue的嵌套应用
# for i in range(1, 6):
# print("语句1")
# for j in range(1, 6):
# print("语句2")
# continue
# print("语句3")
#
# print("语句4")
# 演示循环中断语句 break
# for i in range(1, 101):
# print("语句1")
# break
# print("语句2")
#
# print("语句3")
# 演示break的嵌套应用
for i in range(1, 6):
print("语句1")
for j in range(1, 6):
print("语句2")
break
print("语句3")
print("语句4")
print(num)
age = int(input("请输入您的年龄:"))
if age >= 18:
if age < 30:
print("年龄满足继续判断")
if int(input("请输入您入职已有多少年:")) > 2:
print("年龄符合且入职超过2年,满足条件,可以领取")
exit()
else:
print("入职时间不满足继续判断")
if int(input("请输入您的职位级别:")) > 3:
print("年龄符合且级别超过3级,满足条件,可以领取")
else:
print("不好意思,您不满足领取条件")
else:
print("不好意思,年龄大于30岁,不满足领取条件。")
else:
print("不好意思,年龄小于18岁,不满足领取条件。")
\ No newline at end of file
# print("Hello", end='')
# print("world", end='')
print("Hello\tWorld")
print("itheima\tbest")
"""
演示:快速体验函数的开发及应用
"""
# 需求,统计字符串的长度,不使用内置函数len()
print("欢迎来到黑马程序员!请出示您的健康码以及72小时核酸证明,并配合测量体温!")
print("体温测量中,您的体温是:37.3度,体温正常请进!")
"""
演示函数的定义语法
"""
# 定义一个函数,输出相关信息
def say_hi():
print("Hi 我是黑马程序员,学Python来黑马")
# 调用函数,让定义的函数开始工作
say_hi()
"""
演示函数基础定义练习案例:自动查核酸
"""
# 定义函数
def check():
# 编写函数体输出信息
print("欢迎来到黑马程序员!\n请出示您的健康码以及72小时核酸证明!")
# 调用函数
check()
"""
演示对list列表的循环,使用while和for循环2种方式
"""
def list_while_func():
"""
使用while循环遍历列表的演示函数
:return: None
"""
my_list = ["传智教育", "黑马程序员", "Python"]
# 循环控制变量通过下标索引来控制,默认0
# 每一次循环将下标索引变量+1
# 循环条件:下标索引变量 < 列表的元素数量
# 定义一个变量用来标记列表的下标
index = 0 # 初始值为0
while index < len(my_list):
# 通过index变量取出对应下标的元素
element = my_list[index]
print(f"列表的元素:{element}")
# 至关重要 将循环变量(index)每一次循环都+1
index += 1
def list_for_func():
"""
使用for循环遍历列表的演示函数
:return: None
"""
my_list = [1, 2, 3, 4, 5]
# for 临时变量 in 数据容器:
for element in my_list:
print(f"列表的元素有:{element}")
# list_while_func()
list_for_func()
"""
演示函数使用参数
"""
# 定义2数相加的函数,通过参数接收被计算的2个数字
def add(x, y, z):
result = x + y + z
print(f"{x} + {y} + {z}的计算结果是:{result}")
# 调用函数,传入被计算的2个数字
add(5, 6, 7)
"""
演示函数的参数练习案例:升级自动查核酸
"""
# 定义函数,接收1个形式参数,数字类型,表示体温
def check(num):
# 在函数体内进行判断体温
print("欢迎来到黑马程序员!请出示您的健康码以及72小时核酸证明,并配合测量体温!")
if num <= 37.5:
print(f"体温测量中,您的体温是:{num}度,体温正常请进!")
else:
print(f"体温测量中,您的体温是:{num}度,需要隔离!")
# 调用函数,传入实际参数
check(37.6)
"""
演示:定义函数返回值的语法格式
"""
# 定义一个函数,完成2数相加功能
def add(a, b):
result = a + b
# 通过返回值,将相加的结果返回给调用者
return result
# 返回结果后,还想输出一句话
print("我完事了")
# 函数的返回值,可以通过变量去接收
r = add(5, 6)
print(r)
"""
演示特殊字面量:None
"""
# 无return语句的函数返回值
def say_hi():
print("你好呀")
result = say_hi()
print(f"无返回值函数,返回的内容是:{result}")
print(f"无返回值函数,返回的内容类型是:{type(result)}")
# 主动返回None的函数
def say_hi2():
print("你好呀")
return None
result = say_hi2()
print(f"无返回值函数,返回的内容是:{result}")
print(f"无返回值函数,返回的内容类型是:{type(result)}")
# None用于if判断
def check_age(age):
if age > 18:
return "SUCCESS"
else:
return None
result = check_age(16)
if not result:
# 进入if表示result是None值 也就是False
print("未成年,不可以进入")
# None用于声明无初始内容的变量
name = None
"""
演示对函数进行文档说明
"""
# 定义函数,进行文档说明
def add(x, y):
"""
add函数可以接收2个参数,进行2数相加的功能
:param x: 形参x表示相加的其中一个数字
:param y: 形参y表示相加的另一个数字
:return: 返回值是2数相加的结果
"""
result = x + y
print(f"2数相加的结果是:{result}")
return result
add(5, 6)
"""
演示嵌套调用函数
"""
# 定义函数func_b
def func_b():
print("---2---")
# 定义函数func_a,并在内部调用func_b
def func_a():
print("---1---")
# 嵌套调用func_b
func_b()
print("---3---")
# 调用函数func_a
func_a()
"""
演示在函数使用的时候,定义的变量作用域
"""
# 演示局部变量
# def test_a():
# num = 100
# print(num)
#
#
# test_a()
# 出了函数体,局部变量就无法使用了
# print(num)
# 演示全局变量
# num = 200
#
# def test_a():
# print(f"test_a: {num}")
#
# def test_b():
# print(f"test_b: {num}")
#
# test_a()
# test_b()
# print(num)
# 在函数内修改全局变量
# num = 200
#
# def test_a():
# print(f"test_a: {num}")
#
# def test_b():
# num = 500 # 局部变量
# print(f"test_b: {num}")
#
# test_a()
# test_b()
# print(num)
# global关键字,在函数内声明变量为全局变量
num = 200
def test_a():
print(f"test_a: {num}")
def test_b():
global num # 设置内部定义的变量为全局变量
num = 500
print(f"test_b: {num}")
test_a()
test_b()
print(num)
"""
演示函数综合案例开发
"""
# 定义全局变量money name
money = 5000000
name = None
# 要求客户输入姓名
name = input("请输入您的姓名:")
# 定义查询函数
def query(show_header):
if show_header:
print("-------------查询余额------------")
print(f"{name},您好,您的余额剩余:{money}元")
# 定义存款函数
def saving(num):
global money # money在函数内部定义为全局变量
money += num
print("-------------存款------------")
print(f"{name},您好,您存款{num}元成功。")
# 调用query函数查询余额
query(False)
# 定义取款函数
def get_money(num):
global money
money -= num
print("-------------取款------------")
print(f"{name},您好,您取款{num}元成功。")
# 调用query函数查询余额
query(False)
# 定义主菜单函数
def main():
print("-------------主菜单------------")
print(f"{name},您好,欢迎来到黑马银行ATM。请选择操作:")
print("查询余额\t[输入1]")
print("存款\t\t[输入2]")
print("取款\t\t[输入3]") # 通过\t制表符对齐输出
print("退出\t\t[输入4]")
return input("请输入您的选择:")
# 设置无限循环,确保程序不退出
while True:
keyboard_input = main()
if keyboard_input == "1":
query(True)
continue # 通过continue继续下一次循环,一进来就是回到了主菜单
elif keyboard_input == "2":
num = int(input("您想要存多少钱?请输入:"))
saving(num)
continue
elif keyboard_input == "3":
num = int(input("您想要取多少钱?请输入:"))
get_money(num)
continue
else:
print("程序退出啦")
break # 通过break退出循环
print("----------------主菜单------------------")
print("周杰轮,您好,欢迎来到黑马银行ATM。请选择操作:")
print("查询余额\t[输入1]")
print("存款\t\t[输入2]")
print("取款\t\t[输入3]")
print("退出\t\t[输入4]")
input("请输入您的选择:")
print()
print("----------------查询余额------------------")
print("周杰轮,您好,您的余额剩余:5000000元")
print("------------------------------")
print("----------------取款------------------")
print("周杰轮,您好,您取款50000元成功")
print("周杰轮,您好,您的余额剩余:4950000元")
"""
演示函数的多返回值示例
"""
# 演示使用多个变量,接收多个返回值
def test_return():
return 1, "hello", True
x, y, z = test_return()
print(x)
print(y)
print(z)
"""
演示多种传参的形式
"""
def user_info(name, age, gender):
print(f"姓名是:{name}, 年龄是:{age}, 性别是:{gender}")
# 位置参数 - 默认使用形式
user_info('小明', 20, '男')
# 关键字参数
user_info(name='小王', age=11, gender='女')
user_info(age=10, gender='女', name='潇潇') # 可以不按照参数的定义顺序传参
user_info('甜甜', gender='女', age=9)
# 缺省参数(默认值)
def user_info(name, age, gender):
print(f"姓名是:{name}, 年龄是:{age}, 性别是:{gender}")
user_info('小天', 13, '男')
# 不定长 - 位置不定长, *号
# 不定长定义的形式参数会作为元组存在,接收不定长数量的参数传入
def user_info(*args):
print(f"args参数的类型是:{type(args)},内容是:{args}")
user_info(1, 2, 3, '小明', '男孩')
# 不定长 - 关键字不定长, **号
def user_info(**kwargs):
print(f"args参数的类型是:{type(kwargs)},内容是:{kwargs}")
user_info(name='小王', age=11, gender='男孩')
"""
演示函数作为参数传递
"""
# 定义一个函数,接收另一个函数作为传入参数
def test_func(compute):
result = compute(1, 2) # 确定compute是函数
print(f"compute参数的类型是:{type(compute)}")
print(f"计算结果:{result}")
# 定义一个函数,准备作为参数传入另一个函数
def compute(x, y):
return x + y
# 调用,并传入函数
test_func(compute)
"""
演示lambda匿名函数
"""
# 定义一个函数,接受其它函数输入
def test_func(compute):
result = compute(1, 2)
print(f"结果是:{result}")
# 通过lambda匿名函数的形式,将匿名函数作为参数传入
def add(x, y):
return x + y
test_func(add)
test_func(lambda x, y: x + y)
def compute(add):
add(1, 2)
def add(x, y):
print(x + y)
compute(lambda x, y: print(x + y))
\ No newline at end of file
"""
演示数据容器之:list列表
语法:[元素,元素,....]
"""
# 定义一个列表 list
my_list = ["itheima", "itcast", "python"]
print(my_list)
print(type(my_list))
my_list = ["itheima", 666, True]
print(my_list)
print(type(my_list))
# 定义一个嵌套的列表
my_list = [ [1, 2, 3], [4, 5, 6]]
print(my_list)
print(type(my_list))
# 通过下标索引取出对应位置的数据
my_list = ["Tom", "Lily", "Rose"]
# 列表[下标索引], 从前向后从0开始,每次+1, 从后向前从-1开始,每次-1
print(my_list[0])
print(my_list[1])
print(my_list[2])
# 错误示范;通过下标索引取数据,一定不要超出范围
# print(my_list[3])
# 通过下标索引取出数据(倒序取出)
print(my_list[-1])
print(my_list[-2])
print(my_list[-3])
# 取出嵌套列表的元素
my_list = [ [1, 2, 3], [4, 5, 6]]
print(my_list[1][1])
"""
演示数据容器之:list列表的常用操作
"""
mylist = ["itcast", "itheima", "python"]
# 1.1 查找某元素在列表内的下标索引
index = mylist.index("itheima")
print(f"itheima在列表中的下标索引值是:{index}")
# 1.2如果被查找的元素不存在,会报错
# index = mylist.index("hello")
# print(f"hello在列表中的下标索引值是:{index}")
# 2. 修改特定下标索引的值
mylist[0] = "传智教育"
print(f"列表被修改元素值后,结果是:{mylist}")
# 3. 在指定下标位置插入新元素
mylist.insert(1, "best")
print(f"列表插入元素后,结果是:{mylist}")
# 4. 在列表的尾部追加```单个```新元素
mylist.append("黑马程序员")
print(f"列表在追加了元素后,结果是:{mylist}")
# 5. 在列表的尾部追加```一批```新元素
mylist2 = [1, 2, 3]
mylist.extend(mylist2)
print(f"列表在追加了一个新的列表后,结果是:{mylist}")
# 6. 删除指定下标索引的元素(2种方式)
mylist = ["itcast", "itheima", "python"]
# 6.1 方式1:del 列表[下标]
del mylist[2]
print(f"列表删除元素后结果是:{mylist}")
# 6.2 方式2:列表.pop(下标)
mylist = ["itcast", "itheima", "python"]
element = mylist.pop(2)
print(f"通过pop方法取出元素后列表内容:{mylist}, 取出的元素是:{element}")
# 7. 删除某元素在列表中的第一个匹配项
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
mylist.remove("itheima")
print(f"通过remove方法移除元素后,列表的结果是:{mylist}")
# 8. 清空列表
mylist.clear()
print(f"列表被清空了,结果是:{mylist}")
# 9. 统计列表内某元素的数量
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
count = mylist.count("itheima")
print(f"列表中itheima的数量是:{count}")
# 10. 统计列表中全部的元素数量
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
count = len(mylist)
print(f"列表的元素数量总共有:{count}个")
"""
演示List常用操作的课后练习
"""
# 1. 定义这个列表,并用变量接收它, 内容是:[21, 25, 21, 23, 22, 20]
mylist = [21, 25, 21, 23, 22, 20]
# 2. 追加一个数字31,到列表的尾部
mylist.append(31)
# 3. 追加一个新列表[29, 33, 30],到列表的尾部
mylist.extend([29, 33, 30])
# 4. 取出第一个元素(应是:21)
num1 = mylist[0]
print(f"从列表中取出来第一个元素,应该是21,实际上是:{num1}")
# 5. 取出最后一个元素(应是:30)
num2 = mylist[-1]
print(f"从列表中取出来最后一个元素,应该是30,实际上是:{num2}")
# 6. 查找元素31,在列表中的下标位置
index = mylist.index(31)
print(f"元素31在列表的下标位置是:{index}")
print(f"最后列表的内容是:{mylist}")
"""
演示使用while和for循环遍历列表
"""
def list_while_func():
"""
使用while循环遍历列表的演示函数
:return: None
"""
mylist = ["传智教育", "黑马程序员", "Python"]
# 循环控制变量:通过下标索引来控制,默认0
# 每一次循环将下标苏姚
def list_for_func():
"""
使用for循环遍历列表的演示函数
:return:
"""
"""
演示tuple元组的定义和操作
"""
# 定义元组
t1 = (1, "Hello", True)
t2 = ()
t3 = tuple()
print(f"t1的类型是:{type(t1)}, 内容是:{t1}")
print(f"t2的类型是:{type(t2)}, 内容是:{t2}")
print(f"t3的类型是:{type(t3)}, 内容是:{t3}")
# 定义单个元素的元素
t4 = ("hello", )
print(f"t4的类型是:{type(t4)}, t4的内容是:{t4}")
# 元组的嵌套
t5 = ( (1, 2, 3), (4, 5, 6) )
print(f"t5的类型是:{type(t5)}, 内容是:{t5}")
# 下标索引去取出内容
num = t5[1][2]
print(f"从嵌套元组中取出的数据是:{num}")
# 元组的操作:index查找方法
t6 = ("传智教育", "黑马程序员", "Python")
index = t6.index("黑马程序员")
print(f"在元组t6中查找黑马程序员,的下标是:{index}")
# 元组的操作:count统计方法
t7 = ("传智教育", "黑马程序员", "黑马程序员", "黑马程序员", "Python")
num = t7.count("黑马程序员")
print(f"在元组t7中统计黑马程序员的数量有:{num}个")
# 元组的操作:len函数统计元组元素数量
t8 = ("传智教育", "黑马程序员", "黑马程序员", "黑马程序员", "Python")
num = len(t8)
print(f"t8元组中的元素有:{num}个")
# 元组的遍历:while
index = 0
while index < len(t8):
print(f"元组的元素有:{t8[index]}")
# 至关重要
index += 1
# 元组的遍历:for
for element in t8:
print(f"2元组的元素有:{element}")
# 修改元组内容
# t8[0] = "itcast"
# 定义一个元组
t9 = (1, 2, ["itheima", "itcast"])
print(f"t9的内容是:{t9}")
t9[2][0] = "黑马程序员"
t9[2][1] = "传智教育"
print(f"t9的内容是:{t9}")
\ No newline at end of file
"""
演示以数据容器的角色,学习字符串的相关操作
"""
my_str = "itheima and itcast"
# 通过下标索引取值
value = my_str[2]
value2 = my_str[-16]
print(f"从字符串{my_str}取下标为2的元素,。值是:{value},取下标为-16的元素。值是:{value2}")
# my_str[2] = "H"
# index方法
value = my_str.index("and")
print(f"在字符串{my_str}中查找and,其起始下标是:{value}")
# replace方法
new_my_str = my_str.replace("it", "程序")
print(f"将字符串{my_str},进行替换后得到:{new_my_str}")
# split方法
my_str = "hello python itheima itcast"
my_str_list = my_str.split(" ")
print(f"将字符串{my_str}进行split切分后得到:{my_str_list}, 类型是:{type(my_str_list)}")
# strip方法
my_str = " itheima and itcast "
new_my_str = my_str.strip() # 不传入参数,去除首尾空格
print(f"字符串{my_str}被strip后,结果:{new_my_str}")
my_str = "12itheima and itcast21"
new_my_str = my_str.strip("12")
print(f"字符串{my_str}被strip('12')后,结果:{new_my_str}")
# 统计字符串中某字符串的出现次数, count
my_str = "itheima and itcast"
count = my_str.count("it")
print(f"字符串{my_str}中it出现的次数是:{count}")
# 统计字符串的长度, len()
num = len(my_str)
print(f"字符串{my_str}的长度是:{num}")
"""
字符串课后练习演示
"itheima itcast boxuegu"
"""
my_str = "itheima itcast boxuegu"
# 统计字符串内有多少个"it"字符
num = my_str.count("it")
print(f"字符串{my_str}中有{num}个it字符")
# 将字符串内的空格,全部替换为字符:"|"
new_my_str = my_str.replace(" ", "|")
print(f"字符串{my_str}被替换空格后,结果是:{new_my_str}")
# 并按照"|"进行字符串分割,得到列表
my_str_list = new_my_str.split("|")
print(f"字符串{new_my_str}按照|分割后结果是:{my_str_list}")
"""
演示对序列进行切片操作
"""
# 对list进行切片,从1开始,4结束,步长1
my_list = [0, 1, 2, 3, 4, 5, 6]
result1 = my_list[1:4] # 步长默认是1,所以可以省略不写
print(f"结果1:{result1}")
# 对tuple进行切片,从头开始,到最后结束,步长1
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result2 = my_tuple[:] # 起始和结束不写表示从头到尾,步长为1可以省略
print(f"结果2:{result2}")
# 对str进行切片,从头开始,到最后结束,步长2
my_str = "01234567"
result3 = my_str[::2]
print(f"结果3:{result3}")
# 对str进行切片,从头开始,到最后结束,步长-1
my_str = "01234567"
result4 = my_str[::-1] # 等同于将序列反转了
print(f"结果4:{result4}")
# 对列表进行切片,从3开始,到1结束,步长-1
my_list = [0, 1, 2, 3, 4, 5, 6]
result5 = my_list[3:1:-1]
print(f"结果5:{result5}")
# 对元组进行切片,从头开始,到尾结束,步长-2
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result6 = my_tuple[::-2]
print(f"结果6:{result6}")
"""
演示序列的切片的课后练习
"万过薪月,员序程马黑来,nohtyP学"
"""
my_str = "万过薪月,员序程马黑来,nohtyP学"
# 倒序字符串,切片取出
result1 = my_str[::-1][9:14]
print(f"方式1结果:{result1}")
# 切片取出,然后倒序
result2 = my_str[5:10][::-1]
print(f"方式2结果:{result2}")
# split分隔"," replace替换"来"为空,倒序字符串
result3 = my_str.split(",")[1].replace("来", "")[::-1]
print(f"方式3结果:{result3}")
"""
演示数据容器集合的使用
"""
# 定义集合
my_set = {"传智教育", "黑马程序员", "itheima", "传智教育", "黑马程序员", "itheima", "传智教育", "黑马程序员", "itheima"}
my_set_empty = set() # 定义空集合
print(f"my_set的内容是:{my_set}, 类型是:{type(my_set)}")
print(f"my_set_empty的内容是:{my_set_empty}, 类型是:{type(my_set_empty)}")
# 添加新元素
my_set.add("Python")
my_set.add("传智教育") #
print(f"my_set添加元素后结果是:{my_set}")
# 移除元素
my_set.remove("黑马程序员")
print(f"my_set移除黑马程序员后,结果是:{my_set}")
# 随机取出一个元素
my_set = {"传智教育", "黑马程序员", "itheima"}
element = my_set.pop()
print(f"集合被取出元素是:{element}, 取出元素后:{my_set}")
# 清空集合, clear
my_set.clear()
print(f"集合被清空啦,结果是:{my_set}")
# 取2个集合的差集
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.difference(set2)
print(f"取出差集后的结果是:{set3}")
print(f"取差集后,原有set1的内容:{set1}")
print(f"取差集后,原有set2的内容:{set2}")
# 消除2个集合的差集
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set1.difference_update(set2)
print(f"消除差集后,集合1结果:{set1}")
print(f"消除差集后,集合2结果:{set2}")
# 2个集合合并为1个
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.union(set2)
print(f"2集合合并结果:{set3}")
print(f"合并后集合1:{set1}")
print(f"合并后集合2:{set2}")
# 统计集合元素数量len()
set1 = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5}
num = len(set1)
print(f"集合内的元素数量有:{num}个")
# 集合的遍历
# 集合不支持下标索引,不能用while循环
# 可以用for循环
set1 = {1, 2, 3, 4, 5}
for element in set1:
print(f"集合的元素有:{element}")
"""
演示集合的课后练习题
my_list = ['黑马程序员', '传智播客', '黑马程序员', '传智播客',
'itheima', 'itcast', 'itheima', 'itcast', 'best']
"""
my_list = ['黑马程序员', '传智播客', '黑马程序员', '传智播客',
'itheima', 'itcast', 'itheima', 'itcast', 'best']
# 定义一个空集合
my_set = set()
# 通过for循环遍历列表
for element in my_list:
# 在for循环中将列表的元素添加至集合
my_set.add(element)
# 最终得到元素去重后的集合对象,并打印输出
print(f"列表的内容是:{my_list}")
print(f"通过for循环后,得到的集合对象是:{my_set}")
"""
演示数据容器字典的定义
"""
# 定义字典
my_dict1 = {"王力鸿": 99, "周杰轮": 88, "林俊节": 77}
# 定义空字典
my_dict2 = {}
my_dict3 = dict()
print(f"字典1的内容是:{my_dict1}, 类型:{type(my_dict1)}")
print(f"字典2的内容是:{my_dict2}, 类型:{type(my_dict2)}")
print(f"字典3的内容是:{my_dict3}, 类型:{type(my_dict3)}")
# 定义重复Key的字典
my_dict1 = {"王力鸿": 99, "王力鸿": 88, "林俊节": 77}
print(f"重复key的字典的内容是:{my_dict1}")
# 从字典中基于Key获取Value
my_dict1 = {"王力鸿": 99, "周杰轮": 88, "林俊节": 77}
score = my_dict1["王力鸿"]
print(f"王力鸿的考试分数是:{score}")
score = my_dict1["周杰轮"]
print(f"周杰轮的考试分数是:{score}")
# 定义嵌套字典
stu_score_dict = {
"王力鸿": {
"语文": 77,
"数学": 66,
"英语": 33
}, "周杰轮": {
"语文": 88,
"数学": 86,
"英语": 55
}, "林俊节": {
"语文": 99,
"数学": 96,
"英语": 66
}
}
print(f"学生的考试信息是:{stu_score_dict}")
# 从嵌套字典中获取数据
# 看一下周杰轮的语文信息
score = stu_score_dict["周杰轮"]["语文"]
print(f"周杰轮的语文分数是:{score}")
score = stu_score_dict["林俊节"]["英语"]
print(f"林俊节的英语分数是:{score}")
"""
演示字典的常用操作
"""
my_dict = {"周杰轮": 99, "林俊节": 88, "张学油": 77}
# 新增元素
my_dict["张信哲"] = 66
print(f"字典经过新增元素后,结果:{my_dict}")
# 更新元素
my_dict["周杰轮"] = 33
print(f"字典经过更新后,结果:{my_dict}")
# 删除元素
score = my_dict.pop("周杰轮")
print(f"字典中被移除了一个元素,结果:{my_dict}, 周杰轮的考试分数是:{score}")
# 清空元素, clear
my_dict.clear()
print(f"字典被清空了,内容是:{my_dict}")
# 获取全部的key
my_dict = {"周杰轮": 99, "林俊节": 88, "张学油": 77}
keys = my_dict.keys()
print(f"字典的全部keys是:{keys}")
# 遍历字典
# 方式1:通过获取到全部的key来完成遍历
for key in keys:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
# 方式2:直接对字典进行for循环,每一次循环都是直接得到key
for key in my_dict:
print(f"2字典的key是:{key}")
print(f"2字典的value是:{my_dict[key]}")
# 统计字典内的元素数量, len()函数
num = len(my_dict)
print(f"字典中的元素数量有:{num}个")
"""
演示字典的课后练习:升职加薪,对所有级别为1级的员工,级别上升1级,薪水增加1000元
"""
# 组织字典记录数据
info_dict = {
"王力鸿": {
"部门": "科技部",
"工资": 3000,
"级别": 1
},
"周杰轮": {
"部门": "市场部",
"工资": 5000,
"级别": 2
},
"林俊节": {
"部门": "市场部",
"工资": 7000,
"级别": 3
},
"张学油": {
"部门": "科技部",
"工资": 4000,
"级别": 1
},
"刘德滑": {
"部门": "市场部",
"工资": 6000,
"级别": 2
}
}
print(f"员工在升值加薪之前的结果:{info_dict}")
# for循环遍历字典
for name in info_dict:
# if条件判断符合条件员工
if info_dict[name]["级别"] == 1:
# 升职加薪操作
# 获取到员工的信息字典
employee_info_dict = info_dict[name]
# 修改员工的信息
employee_info_dict["级别"] = 2 # 级别+1
employee_info_dict["工资"] += 1000 # 工资+1000
# 将员工的信息更新回info_dict
info_dict[name] = employee_info_dict
# 输出结果
print(f"对员工进行升级加薪后的结果是:{info_dict}")
"""
演示数据容器的通用功能
"""
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, "key4": 4, "key5": 5}
# 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)}")
# 类型转换: 容器转列表
print(f"列表转列表的结果是:{list(my_list)}")
print(f"元组转列表的结果是:{list(my_tuple)}")
print(f"字符串转列表结果是:{list(my_str)}")
print(f"集合转列表的结果是:{list(my_set)}")
print(f"字典转列表的结果是:{list(my_dict)}")
# 类型转换: 容器转元组
print(f"列表转元组的结果是:{tuple(my_list)}")
print(f"元组转元组的结果是:{tuple(my_tuple)}")
print(f"字符串转元组结果是:{tuple(my_str)}")
print(f"集合转元组的结果是:{tuple(my_set)}")
print(f"字典转元组的结果是:{tuple(my_dict)}")
# 类型转换: 容器转字符串
print(f"列表转字符串的结果是:{str(my_list)}")
print(f"元组转字符串的结果是:{str(my_tuple)}")
print(f"字符串转字符串结果是:{str(my_str)}")
print(f"集合转字符串的结果是:{str(my_set)}")
print(f"字典转字符串的结果是:{str(my_dict)}")
# 类型转换: 容器转集合
print(f"列表转集合的结果是:{set(my_list)}")
print(f"元组转集合的结果是:{set(my_tuple)}")
print(f"字符串转集合结果是:{set(my_str)}")
print(f"集合转集合的结果是:{set(my_set)}")
print(f"字典转集合的结果是:{set(my_dict)}")
# 进行容器的排序
my_list = [3, 1, 2, 5, 4]
my_tuple = (3, 1, 2, 5, 4)
my_str = "bdcefga"
my_set = {3, 1, 2, 5, 4}
my_dict = {"key3": 1, "key1": 2, "key2": 3, "key5": 4, "key4": 5}
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)}")
"""
演示字符串大小比较
"""
# abc 比较 abd
print(f"abd大于abc,结果:{'abd' > 'abc'}")
# a 比较 ab
print(f"ab大于a,结果:{'ab' > 'a'}")
# a 比较 A
print(f"a 大于 A,结果:{'a' > 'A'}")
# key1 比较 key2
print(f"key2 > key1,结果:{'key2' > 'key1'}")
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = []
i = 0
while i < len(my_list):
if my_list[i] % 2 == 0:
new_list.append(my_list[i])
i += 1
print(f"偶数形成的新列表:{new_list}")
"""
演示对文件的读取
"""
# 打开文件
import time
f = open("D:/测试.txt", "r", encoding="UTF-8")
print(type(f))
# 读取文件 - read()
# print(f"读取10个字节的结果:{f.read(10)}")
# print(f"read方法读取全部内容的结果是:{f.read()}")
print("-----------------------------------------------")
# 读取文件 - readLines()
# lines = f.readlines() # 读取文件的全部行,封装到列表中
# print(f"lines对象的类型:{type(lines)}")
# print(f"lines对象的内容是:{lines}")
# 读取文件 - readline()
# line1 = f.readline()
# line2 = f.readline()
# line3 = f.readline()
# print(f"第一行数据是:{line1}")
# print(f"第二行数据是:{line2}")
# print(f"第三行数据是:{line3}")
# for循环读取文件行
# for line in f:
# print(f"每一行数据是:{line}")
# # 文件的关闭
# f.close()
# time.sleep(500000)
# with open 语法操作文件
with open("D:/测试.txt", "r", encoding="UTF-8") as f:
for line in f:
print(f"每一行数据是:{line}")
time.sleep(500000)
\ No newline at end of file
"""
演示读取文件,课后练习题
"""
# 打开文件,以读取模式打开
f = open("D:/word.txt", "r", encoding="UTF-8")
# 方式1:读取全部内容,通过字符串count方法统计itheima单词数量
# content = f.read()
# count = content.count("itheima")
# print(f"itheima在文件中出现了:{count}次")
# 方式2:读取内容,一行一行读取
count = 0 # 使用count变量来累计itheima出现的次数
for line in f:
line = line.strip() # 去除开头和结尾的空格以及换行符
words = line.split(" ")
for word in words:
if word == "itheima":
count += 1 # 如果单词是itheima,进行数量的累加加1
# 判断单词出现次数并累计
print(f"itheima出现的次数是:{count}")
# 关闭文件
f.close()
"""
演示文件的写入
"""
# 打开文件,不存在的文件, r, w, a
import time
# f = open("D:/test.txt", "w", encoding="UTF-8")
# # write写入
# f.write("Hello World!!!") # 内容写入到内存中
# # flush刷新
# # f.flush() # 将内存中积攒的内容,写入到硬盘的文件中
# # close关闭
# f.close() # close方法,内置了flush的功能的
# 打开一个存在的文件
f = open("D:/test.txt", "w", encoding="UTF-8")
# write写入、flush刷新
f.write("黑马程序员")
# close关闭
f.close()
"""
演示文件的追加写入
"""
# 打开文件,不存在的文件
# f = open("D:/test.txt", "a", encoding="UTF-8")
# # write写入
# f.write("黑马程序员")
# # flush刷新
# f.flush()
# # close关闭
# f.close()
# 打开一个存在的文件
f = open("D:/test.txt", "a", encoding="UTF-8")
# write写入、flush刷新
f.write("\n月薪过万")
# close关闭
f.close()
"""
演示文件操作综合案例:文件备份
"""
# 打开文件得到文件对象,准备读取
fr = open("D:/bill.txt", "r", encoding="UTF-8")
# 打开文件得到文件对象,准备写入
fw = open("D:/bill.txt.bak", "w", encoding="UTF-8")
# for循环读取文件
for line in fr:
line = line.strip()
# 判断内容,将满足的内容写出
if line.split(",")[4] == "测试":
continue # continue进入下一次循环,这一次后面的内容就跳过了
# 将内容写出去
fw.write(line)
# 由于前面对内容进行了strip()的操作,所以要手动的写出换行符
fw.write("\n")
# close2个文件对象
fr.close()
fw.close() # 写出文件调用close()会自动flush()
"""
主动写一段错误代码,演示异常的出现
"""
# 通过open,读取一个不存在的文件
f = open("D:/abc.txt", "r", encoding="UTF-8")
"""
演示捕获异常
"""
# 基本捕获语法
# try:
# f = open("D:/abc.txt", "r", encoding="UTF-8")
# except:
# print("出现异常了,因为文件不存在,我将open的模式,改为w模式去打开")
# f = open("D:/abc.txt", "w", encoding="UTF-8")
# 捕获指定的异常
# try:
# print(name)
# # 1 / 0
# except NameError as e:
# print("出现了变量未定义的异常")
# print(e)
# 捕获多个异常
# try:
# # 1 / 0
# print(name)
# except (NameError, ZeroDivisionError) as e:
# print("出现了变量未定义 或者 除以0的异常错误")
# 未正确设置捕获异常类型,将无法捕获异常
# 捕获所有异常
try:
f = open("D:/123.txt", "r", encoding="UTF-8")
except Exception as e:
print("出现异常了")
f = open("D:/123.txt", "w", encoding="UTF-8")
else:
print("好高兴,没有异常。")
finally:
print("我是finally,有没有异常我都要执行")
f.close()
"""
演示异常的传递性
"""
# 定义一个出现异常的方法
def func1():
print("func1 开始执行")
num = 1 / 0 # 肯定有异常,除以0的异常
print("func1 结束执行")
# 定义一个无异常的方法,调用上面的方法
def func2():
print("func2 开始执行")
func1()
print("func2 结束执行")
# 定义一个方法,调用上面的方法
def main():
try:
func2()
except Exception as e:
print(f"出现异常了,异常的信息是:{e}")
main()
"""
演示Python的模块导入
"""
from time import sleep
# 使用import导入time模块使用sleep功能(函数)
# import time # 导入Python内置的time模块(time.py这个代码文件)
# print("你好")
# time.sleep(5) # 通过. 就可以使用模块内部的全部功能(类、函数、变量)
# print("我好")
# 使用from导入time的sleep功能(函数)
# from time import sleep
# print("你好")
# sleep(5)
# print("我好")
# 使用 * 导入time模块的全部功能
# from time import * # *表示全部的意思
# print("你好")
# sleep(5)
# print("我好")
# 使用as给特定功能加上别名
# import time as t
# print("你好")
# t.sleep(5)
# print("我好")
from time import sleep as sl
print("你好")
sl(5)
print("我好")
"""
演示自定义模块
"""
# 导入自定义模块使用
# import my_module1
# from my_module1 import test
# test(1, 2)
# 导入不同模块的同名功能
# from my_module1 import test
# from my_module2 import test
# test(1, 2)
# __main__变量
# from my_module1 import test
# __all__变量
from my_module1 import *
test_a(1, 2)
# test_b(2, 1)
"""
演示Python的包
"""
# 创建一个包
# 导入自定义的包中的模块,并使用
# import my_package.my_module1
# import my_package.my_module2
#
# my_package.my_module1.info_print1()
# my_package.my_module2.info_print2()
# from my_package import my_module1
# from my_package import my_module2
# my_module1.info_print1()
# my_module2.info_print2()
# from my_package.my_module1 import info_print1
# from my_package.my_module2 import info_print2
# info_print1()
# info_print2()
# 通过__all__变量,控制import *
from my_package import *
my_module1.info_print1()
my_module2.info_print2()
"""
演示异常、模块、包的综合案例练习
"""
# 创建my_utils 包, 在包内创建:str_util.py 和 file_util.py 2个模块,并提供相应的函数
import my_utils.str_util
from my_utils import file_util
print(my_utils.str_util.str_reverse("黑马程序员"))
print(my_utils.str_util.substr("itheima", 0, 4))
file_util.append_to_file("D:/test_append.txt", "itheima")
file_util.print_file_info("D:/test_append.txt")
"""
演示常用的模块功能
"""
import time
# time模块
ts = time.time() # 当前时间戳
print(f"当前时间戳是:{ts}")
# 获取当前时间以指定的格式显示,2000-01-01 10:00:00
print(time.strftime("%Y-%m-%d %H:%M:%S"))
# 将指定的时间戳转换为格式化的日期字符串
print(time.strftime("%Y-%m-%d %H:%M:%S"))
# random模块
# os模块
# sys模块
"""
演示JSON数据和Python字典的相互转换
"""
import json
# 准备列表,列表内每一个元素都是字典,将其转换为JSON
data = [{"name": "张大山", "age": 11}, {"name": "王大锤", "age": 13}, {"name": "赵小虎", "age": 16}]
json_str = json.dumps(data, ensure_ascii=False)
print(type(json_str))
print(json_str)
# 准备字典,将字典转换为JSON
d = {"name":"周杰轮", "addr":"台北"}
json_str = json.dumps(d, ensure_ascii=False)
print(type(json_str))
print(json_str)
# 将JSON字符串转换为Python数据类型[{k: v, k: v}, {k: v, k: v}]
s = '[{"name": "张大山", "age": 11}, {"name": "王大锤", "age": 13}, {"name": "赵小虎", "age": 16}]'
l = json.loads(s)
print(type(l))
print(l)
# 将JSON字符串转换为Python数据类型{k: v, k: v}
s = '{"name": "周杰轮", "addr": "台北"}'
d = json.loads(s)
print(type(d))
print(d)
"""
演示pyecharts的基础入门
"""
# 导包
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),
)
# 通过render方法,将代码生成为图像
line.render()
"""
演示可视化需求1:折线图开发
"""
import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LabelOpts
# 处理数据
f_us = open("D:/美国.txt", "r", encoding="UTF-8")
us_data = f_us.read() # 美国的全部内容
f_jp = open("D:/日本.txt", "r", encoding="UTF-8")
jp_data = f_jp.read() # 日本的全部内容
f_in = open("D:/印度.txt", "r", encoding="UTF-8")
in_data = f_in.read() # 印度的全部内容
# 去掉不合JSON规范的开头
us_data = us_data.replace("jsonp_1629344292311_69436(", "")
jp_data = jp_data.replace("jsonp_1629350871167_29498(", "")
in_data = in_data.replace("jsonp_1629350745930_63180(", "")
# 去掉不合JSON规范的结尾
us_data = us_data[:-2]
jp_data = jp_data[:-2]
in_data = in_data[:-2]
# JSON转Python字典
us_dict = json.loads(us_data)
jp_dict = json.loads(jp_data)
in_dict = json.loads(in_data)
# 获取trend key
us_trend_data = us_dict['data'][0]['trend']
jp_trend_data = jp_dict['data'][0]['trend']
in_trend_data = in_dict['data'][0]['trend']
# 获取日期数据,用于x轴,取2020年(到314下标结束)
us_x_data = us_trend_data['updateDate'][:314]
jp_x_data = jp_trend_data['updateDate'][:314]
in_x_data = in_trend_data['updateDate'][:314]
# 获取确认数据,用于y轴,取2020年(到314下标结束)
us_y_data = us_trend_data['list'][0]['data'][:314]
jp_y_data = jp_trend_data['list'][0]['data'][:314]
in_y_data = in_trend_data['list'][0]['data'][:314]
# 生成图表
line = Line() # 构建折线图对象
# 添加x轴数据
line.add_xaxis(us_x_data) # x轴是公用的,所以使用一个国家的数据即可
# 添加y轴数据
line.add_yaxis("美国确诊人数", us_y_data, label_opts=LabelOpts(is_show=False)) # 添加美国的y轴数据
line.add_yaxis("日本确诊人数", jp_y_data, label_opts=LabelOpts(is_show=False)) # 添加日本的y轴数据
line.add_yaxis("印度确诊人数", in_y_data, label_opts=LabelOpts(is_show=False)) # 添加印度的y轴数据
# 设置全局选项
line.set_global_opts(
# 标题设置
title_opts=TitleOpts(title="2020年美日印三国确诊人数对比折线图", pos_left="center", pos_bottom="1%")
)
# 调用render方法,生成图表
line.render()
# 关闭文件对象
f_us.close()
f_jp.close()
f_in.close()
"""
演示地图可视化的基本使用
"""
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts
# 准备地图对象
map = Map()
# 准备数据
data = [
("北京", 99),
("上海", 199),
("湖南", 299),
("台湾", 399),
("广东", 499)
]
# 添加数据
map.add("测试地图", data, "china")
# 设置全局选项
map.set_global_opts(
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True,
pieces=[
{"min": 1, "max": 9, "label": "1-9", "color": "#CCFFFF"},
{"min": 10, "max": 99, "label": "10-99", "color": "#FF6666"},
{"min": 100, "max": 500, "label": "100-500", "color": "#990033"}
]
)
)
# 绘图
map.render()
"""
演示全国疫情可视化地图开发
"""
import json
from pyecharts.charts import Map
from pyecharts.options import *
# 读取数据文件
f = open("D:/疫情.txt", "r", encoding="UTF-8")
data = f.read() # 全部数据
# 关闭文件
f.close()
# 取到各省数据
# 将字符串json转换为python的字典
data_dict = json.loads(data) # 基础数据字典
# 从字典中取出省份的数据
province_data_list = data_dict["areaTree"][0]["children"]
# 组装每个省份和确诊人数为元组,并各个省的数据都封装入列表内
data_list = [] # 绘图需要用的数据列表
for province_data in province_data_list:
province_name = province_data["name"] # 省份名称
province_confirm = province_data["total"]["confirm"] # 确诊人数
data_list.append((province_name, province_confirm))
# 创建地图对象
map = Map()
# 添加数据
map.add("各省份确诊人数", data_list, "china")
# 设置全局配置,定制分段的视觉映射
map.set_global_opts(
title_opts=TitleOpts(title="全国疫情地图"),
visualmap_opts=VisualMapOpts(
is_show=True, # 是否显示
is_piecewise=True, # 是否分段
pieces=[
{"min": 1, "max": 99, "lable": "1~99人", "color": "#CCFFFF"},
{"min": 100, "max": 999, "lable": "100~9999人", "color": "#FFFF99"},
{"min": 1000, "max": 4999, "lable": "1000~4999人", "color": "#FF9966"},
{"min": 5000, "max": 9999, "lable": "5000~99999人", "color": "#FF6666"},
{"min": 10000, "max": 99999, "lable": "10000~99999人", "color": "#CC3333"},
{"min": 100000, "lable": "100000+", "color": "#990033"},
]
)
)
# 绘图
map.render("全国疫情地图.html")
"""
演示河南省疫情地图开发
"""
import json
from pyecharts.charts import Map
from pyecharts.options import *
# 读取文件
f = open("D:/疫情.txt", "r", encoding="UTF-8")
data = f.read()
# 关闭文件
f.close()
# 获取河南省数据
# json数据转换为python字典
data_dict = json.loads(data)
# 取到河南省数据
cities_data = data_dict["areaTree"][0]["children"][3]["children"]
# 准备数据为元组并放入list
data_list = []
for city_data in cities_data:
city_name = city_data["name"] + "市"
city_confirm = city_data["total"]["confirm"]
data_list.append((city_name, city_confirm))
# 手动添加济源市的数据
data_list.append(("济源市", 5))
# 构建地图
map = Map()
map.add("河南省疫情分布", data_list, "河南")
# 设置全局选项
map.set_global_opts(
title_opts=TitleOpts(title="河南省疫情地图"),
visualmap_opts=VisualMapOpts(
is_show=True, # 是否显示
is_piecewise=True, # 是否分段
pieces=[
{"min": 1, "max": 99, "lable": "1~99人", "color": "#CCFFFF"},
{"min": 100, "max": 999, "lable": "100~9999人", "color": "#FFFF99"},
{"min": 1000, "max": 4999, "lable": "1000~4999人", "color": "#FF9966"},
{"min": 5000, "max": 9999, "lable": "5000~99999人", "color": "#FF6666"},
{"min": 10000, "max": 99999, "lable": "10000~99999人", "color": "#CC3333"},
{"min": 100000, "lable": "100000+", "color": "#990033"},
]
)
)
# 绘图
map.render("河南省疫情地图.html")
"""
演示基础柱状图的开发
"""
from pyecharts.charts import Bar
from pyecharts.options import LabelOpts
# 使用Bar构建基础柱状图
bar = Bar()
# 添加x轴的数据
bar.add_xaxis(["中国", "美国", "英国"])
# 添加y轴数据
bar.add_yaxis("GDP", [30, 20, 10], label_opts=LabelOpts(position="right"))
# 反转x和y轴
bar.reversal_axis()
# 绘图
bar.render("基础柱状图.html")
# 反转x轴和y轴
# 设置数值标签在右侧
\ No newline at end of file
"""
演示带有时间线的柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import LabelOpts
from pyecharts.globals import ThemeType
bar1 = Bar()
bar1.add_xaxis(["中国", "美国", "英国"])
bar1.add_yaxis("GDP", [30, 30, 20], label_opts=LabelOpts(position="right"))
bar1.reversal_axis()
bar2 = Bar()
bar2.add_xaxis(["中国", "美国", "英国"])
bar2.add_yaxis("GDP", [50, 50, 50], label_opts=LabelOpts(position="right"))
bar2.reversal_axis()
bar3 = Bar()
bar3.add_xaxis(["中国", "美国", "英国"])
bar3.add_yaxis("GDP", [70, 60, 60], label_opts=LabelOpts(position="right"))
bar3.reversal_axis()
# 构建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
# 在时间线内添加柱状图对象
timeline.add(bar1, "点1")
timeline.add(bar2, "点2")
timeline.add(bar3, "点3")
# 自动播放设置
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=True
)
# 绘图是用时间线对象绘图,而不是bar对象了
timeline.render("基础时间线柱状图.html")
"""
扩展列表的sort方法
在学习了将函数作为参数传递后,我们可以学习列表的sort方法来对列表进行自定义排序
"""
# 准备列表
my_list = [["a", 33], ["b", 55], ["c", 11]]
# 排序,基于带名函数
# def choose_sort_key(element):
# return element[1]
#
# my_list.sort(key=choose_sort_key, reverse=True)
# 排序,基于lambda匿名函数
my_list.sort(key=lambda element: element[1], reverse=True)
print(my_list)
"""
演示第三个图表:GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
# 读取数据
f = open("D:/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()
# 关闭文件
f.close()
# 删除第一条数据
data_lines.pop(0)
# 将数据转换为字典存储,格式为:
# { 年份: [ [国家, gdp], [国家,gdp], ...... ], 年份: [ [国家, gdp], [国家,gdp], ...... ], ...... }
# { 1960: [ [美国, 123], [中国,321], ...... ], 1961: [ [美国, 123], [中国,321], ...... ], ...... }
# 先定义一个字典对象
data_dict = {}
for line in data_lines:
year = int(line.split(",")[0]) # 年份
country = line.split(",")[1] # 国家
gdp = float(line.split(",")[2]) # gdp数据
# 如何判断字典里面有没有指定的key呢?
try:
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])
# print(data_dict[1960])
# 创建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
# 排序年份
sorted_year_list = sorted(data_dict.keys())
for year in sorted_year_list:
data_dict[year].sort(key=lambda element: element[1], reverse=True)
# 取出本年份前8名的国家
year_data = data_dict[year][0:8]
x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0]) # x轴添加国家
y_data.append(country_gdp[1] / 100000000) # y轴添加gdp数据
# 构建柱状图
bar = Bar()
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis("GDP(亿)", y_data, label_opts=LabelOpts(position="right"))
# 反转x轴和y轴
bar.reversal_axis()
# 设置每一年的图表的标题
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}年全球前8GDP数据")
)
timeline.add(bar, str(year))
# for循环每一年的数据,基于每一年的数据,创建每一年的bar对象
# 在for中,将每一年的bar对象添加到时间线中
# 设置时间线自动播放
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=False
)
# 绘图
timeline.render("1960-2019全球GDP前8国家.html")
此差异已折叠。
import time
# account_amount = 0 # 账户余额
# def atm(num, deposit=True):
# global account_amount
# if deposit:
# account_amount += num
# print(f"存款:+{num},账户余额:{account_amount}")
# else:
# account_amount -= num
# print(f"取款:-{num},账户余额:{account_amount}")
#
#
# atm(300)
# atm(300)
# atm(100, False)
#
#
# def account_create(initial_amount=0):
# def atm(num, deposit=True):
# nonlocal initial_amount
# if deposit:
# initial_amount += num
# print(f"存款:+{num},账户余额:{initial_amount}")
# else:
# initial_amount -= num
# print(f"取款:-{num},账户余额:{initial_amount}")
#
# return atm
#
#
# fn = account_create()
# fn(300)
# fn(200)
# fn(300, False)
#
# def outer(logo):
#
# def inner(msg):
# print(f"<{logo}>{msg}<{logo}>")
#
# return inner
#
#
# fn1 = outer("黑马程序员")
# fn1("大家好呀")
# fn1("学Python就来")
#
# fn2 = outer("传智教育")
# fn2("IT职业教育培训")
# fn2("学Python就来")
# def outer(num1):
#
# def inner(num2):
# nonlocal num1
# num1 += num2
# print(num1)
#
# return inner
#
#
# fn = outer(10)
# fn(10)
# fn(10)
# def outer(func):
# def inner():
# print("我要睡觉了")
# func()
# print("我起床了")
#
# return inner
#
#
# @outer
# def sleep():
# import random
# import time
# print("睡眠中......")
# time.sleep(random.randint(1, 5))
#
#
# sleep()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/maps/china.js"></script>
</head>
<body>
<div id="345a3b147c254be2baae8b48c56b038f" class="chart-container" style="width:900px; height:500px;"></div>
<script>
var chart_345a3b147c254be2baae8b48c56b038f = echarts.init(
document.getElementById('345a3b147c254be2baae8b48c56b038f'), 'white', {renderer: 'canvas'});
var option_345a3b147c254be2baae8b48c56b038f = {
"animation": true,
"animationThreshold": 2000,
"animationDuration": 1000,
"animationEasing": "cubicOut",
"animationDelay": 0,
"animationDurationUpdate": 300,
"animationEasingUpdate": "cubicOut",
"animationDelayUpdate": 0,
"color": [
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
"#f05b72",
"#ef5b9c",
"#f47920",
"#905a3d",
"#fab27b",
"#2a5caa",
"#444693",
"#726930",
"#b2d235",
"#6d8346",
"#ac6767",
"#1d953f",
"#6950a1",
"#918597"
],
"series": [
{
"type": "map",
"name": "\u5404\u7701\u4efd\u786e\u8bca\u4eba\u6570",
"label": {
"show": true,
"position": "top",
"margin": 8
},
"mapType": "china",
"data": [
{
"name": "\u53f0\u6e7e",
"value": 15880
},
{
"name": "\u6c5f\u82cf",
"value": 1576
},
{
"name": "\u4e91\u5357",
"value": 982
},
{
"name": "\u6cb3\u5357",
"value": 1518
},
{
"name": "\u4e0a\u6d77",
"value": 2408
},
{
"name": "\u6e56\u5357",
"value": 1181
},
{
"name": "\u6e56\u5317",
"value": 68286
},
{
"name": "\u5e7f\u4e1c",
"value": 2978
},
{
"name": "\u9999\u6e2f",
"value": 12039
},
{
"name": "\u798f\u5efa",
"value": 773
},
{
"name": "\u6d59\u6c5f",
"value": 1417
},
{
"name": "\u5c71\u4e1c",
"value": 923
},
{
"name": "\u56db\u5ddd",
"value": 1179
},
{
"name": "\u5929\u6d25",
"value": 445
},
{
"name": "\u5317\u4eac",
"value": 1107
},
{
"name": "\u9655\u897f",
"value": 668
},
{
"name": "\u5e7f\u897f",
"value": 289
},
{
"name": "\u8fbd\u5b81",
"value": 441
},
{
"name": "\u91cd\u5e86",
"value": 603
},
{
"name": "\u6fb3\u95e8",
"value": 63
},
{
"name": "\u7518\u8083",
"value": 199
},
{
"name": "\u5c71\u897f",
"value": 255
},
{
"name": "\u6d77\u5357",
"value": 190
},
{
"name": "\u5185\u8499\u53e4",
"value": 410
},
{
"name": "\u5409\u6797",
"value": 574
},
{
"name": "\u9ed1\u9f99\u6c5f",
"value": 1613
},
{
"name": "\u5b81\u590f",
"value": 77
},
{
"name": "\u9752\u6d77",
"value": 18
},
{
"name": "\u6c5f\u897f",
"value": 937
},
{
"name": "\u8d35\u5dde",
"value": 147
},
{
"name": "\u897f\u85cf",
"value": 1
},
{
"name": "\u5b89\u5fbd",
"value": 1008
},
{
"name": "\u6cb3\u5317",
"value": 1317
},
{
"name": "\u65b0\u7586",
"value": 980
}
],
"roam": true,
"aspectScale": 0.75,
"nameProperty": "name",
"selectedMode": false,
"zoom": 1,
"mapValueCalculation": "sum",
"showLegendSymbol": true,
"emphasis": {}
}
],
"legend": [
{
"data": [
"\u5404\u7701\u4efd\u786e\u8bca\u4eba\u6570"
],
"selected": {
"\u5404\u7701\u4efd\u786e\u8bca\u4eba\u6570": true
},
"show": true,
"padding": 5,
"itemGap": 10,
"itemWidth": 25,
"itemHeight": 14
}
],
"tooltip": {
"show": true,
"trigger": "item",
"triggerOn": "mousemove|click",
"axisPointer": {
"type": "line"
},
"showContent": true,
"alwaysShowContent": false,
"showDelay": 0,
"hideDelay": 100,
"textStyle": {
"fontSize": 14
},
"borderWidth": 0,
"padding": 5
},
"title": [
{
"text": "\u5168\u56fd\u75ab\u60c5\u5730\u56fe",
"padding": 5,
"itemGap": 10
}
],
"visualMap": {
"show": true,
"type": "piecewise",
"min": 0,
"max": 100,
"inRange": {
"color": [
"#50a3ba",
"#eac763",
"#d94e5d"
]
},
"calculable": true,
"inverse": false,
"splitNumber": 5,
"orient": "vertical",
"showLabel": true,
"itemWidth": 20,
"itemHeight": 14,
"borderWidth": 0,
"pieces": [
{
"min": 1,
"max": 99,
"lable": "1~99\u4eba",
"color": "#CCFFFF"
},
{
"min": 100,
"max": 999,
"lable": "100~9999\u4eba",
"color": "#FFFF99"
},
{
"min": 1000,
"max": 4999,
"lable": "1000~4999\u4eba",
"color": "#FF9966"
},
{
"min": 5000,
"max": 9999,
"lable": "5000~99999\u4eba",
"color": "#FF6666"
},
{
"min": 10000,
"max": 99999,
"lable": "10000~99999\u4eba",
"color": "#CC3333"
},
{
"min": 100000,
"lable": "100000+",
"color": "#990033"
}
]
}
};
chart_345a3b147c254be2baae8b48c56b038f.setOption(option_345a3b147c254be2baae8b48c56b038f);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
<div id="ab78bbd0ab244ae1bb4babaa3734a166" class="chart-container" style="width:900px; height:500px;"></div>
<script>
var chart_ab78bbd0ab244ae1bb4babaa3734a166 = echarts.init(
document.getElementById('ab78bbd0ab244ae1bb4babaa3734a166'), 'light', {renderer: 'canvas'});
var option_ab78bbd0ab244ae1bb4babaa3734a166 = {
"baseOption": {
"series": [
{
"type": "bar",
"name": "GDP",
"legendHoverLink": true,
"data": [
70,
60,
60
],
"showBackground": false,
"barMinHeight": 0,
"barCategoryGap": "20%",
"barGap": "30%",
"large": false,
"largeThreshold": 400,
"seriesLayoutBy": "column",
"datasetIndex": 0,
"clip": true,
"zlevel": 0,
"z": 2,
"label": {
"show": true,
"position": "right",
"margin": 8
}
}
],
"timeline": {
"axisType": "category",
"orient": "horizontal",
"autoPlay": true,
"controlPosition": "left",
"loop": true,
"rewind": false,
"show": true,
"inverse": false,
"playInterval": 1000,
"bottom": "-5px",
"data": [
"\u70b91",
"\u70b92",
"\u70b93"
]
},
"xAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
}
}
],
"yAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
},
"data": [
"\u4e2d\u56fd",
"\u7f8e\u56fd",
"\u82f1\u56fd"
]
}
]
},
"options": [
{
"legend": [
{
"data": [
"GDP"
],
"selected": {
"GDP": true
}
}
],
"series": [
{
"type": "bar",
"name": "GDP",
"legendHoverLink": true,
"data": [
30,
30,
20
],
"showBackground": false,
"barMinHeight": 0,
"barCategoryGap": "20%",
"barGap": "30%",
"large": false,
"largeThreshold": 400,
"seriesLayoutBy": "column",
"datasetIndex": 0,
"clip": true,
"zlevel": 0,
"z": 2,
"label": {
"show": true,
"position": "right",
"margin": 8
}
}
],
"xAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
}
}
],
"yAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
},
"data": [
"\u4e2d\u56fd",
"\u7f8e\u56fd",
"\u82f1\u56fd"
]
}
],
"tooltip": {
"show": true,
"trigger": "item",
"triggerOn": "mousemove|click",
"axisPointer": {
"type": "line"
},
"showContent": true,
"alwaysShowContent": false,
"showDelay": 0,
"hideDelay": 100,
"textStyle": {
"fontSize": 14
},
"borderWidth": 0,
"padding": 5
},
"color": [
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
"#f05b72",
"#ef5b9c",
"#f47920",
"#905a3d",
"#fab27b",
"#2a5caa",
"#444693",
"#726930",
"#b2d235",
"#6d8346",
"#ac6767",
"#1d953f",
"#6950a1",
"#918597"
]
},
{
"legend": [
{
"data": [
"GDP"
],
"selected": {
"GDP": true
}
}
],
"series": [
{
"type": "bar",
"name": "GDP",
"legendHoverLink": true,
"data": [
50,
50,
50
],
"showBackground": false,
"barMinHeight": 0,
"barCategoryGap": "20%",
"barGap": "30%",
"large": false,
"largeThreshold": 400,
"seriesLayoutBy": "column",
"datasetIndex": 0,
"clip": true,
"zlevel": 0,
"z": 2,
"label": {
"show": true,
"position": "right",
"margin": 8
}
}
],
"xAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
}
}
],
"yAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
},
"data": [
"\u4e2d\u56fd",
"\u7f8e\u56fd",
"\u82f1\u56fd"
]
}
],
"tooltip": {
"show": true,
"trigger": "item",
"triggerOn": "mousemove|click",
"axisPointer": {
"type": "line"
},
"showContent": true,
"alwaysShowContent": false,
"showDelay": 0,
"hideDelay": 100,
"textStyle": {
"fontSize": 14
},
"borderWidth": 0,
"padding": 5
},
"color": [
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
"#f05b72",
"#ef5b9c",
"#f47920",
"#905a3d",
"#fab27b",
"#2a5caa",
"#444693",
"#726930",
"#b2d235",
"#6d8346",
"#ac6767",
"#1d953f",
"#6950a1",
"#918597"
]
},
{
"legend": [
{
"data": [
"GDP"
],
"selected": {
"GDP": true
}
}
],
"series": [
{
"type": "bar",
"name": "GDP",
"legendHoverLink": true,
"data": [
70,
60,
60
],
"showBackground": false,
"barMinHeight": 0,
"barCategoryGap": "20%",
"barGap": "30%",
"large": false,
"largeThreshold": 400,
"seriesLayoutBy": "column",
"datasetIndex": 0,
"clip": true,
"zlevel": 0,
"z": 2,
"label": {
"show": true,
"position": "right",
"margin": 8
}
}
],
"xAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
}
}
],
"yAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
},
"data": [
"\u4e2d\u56fd",
"\u7f8e\u56fd",
"\u82f1\u56fd"
]
}
],
"tooltip": {
"show": true,
"trigger": "item",
"triggerOn": "mousemove|click",
"axisPointer": {
"type": "line"
},
"showContent": true,
"alwaysShowContent": false,
"showDelay": 0,
"hideDelay": 100,
"textStyle": {
"fontSize": 14
},
"borderWidth": 0,
"padding": 5
},
"color": [
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
"#f05b72",
"#ef5b9c",
"#f47920",
"#905a3d",
"#fab27b",
"#2a5caa",
"#444693",
"#726930",
"#b2d235",
"#6d8346",
"#ac6767",
"#1d953f",
"#6950a1",
"#918597"
]
}
]
};
chart_ab78bbd0ab244ae1bb4babaa3734a166.setOption(option_ab78bbd0ab244ae1bb4babaa3734a166);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
<div id="0182a594b6314cb395f04c7eabd37276" class="chart-container" style="width:900px; height:500px;"></div>
<script>
var chart_0182a594b6314cb395f04c7eabd37276 = echarts.init(
document.getElementById('0182a594b6314cb395f04c7eabd37276'), 'white', {renderer: 'canvas'});
var option_0182a594b6314cb395f04c7eabd37276 = {
"animation": true,
"animationThreshold": 2000,
"animationDuration": 1000,
"animationEasing": "cubicOut",
"animationDelay": 0,
"animationDurationUpdate": 300,
"animationEasingUpdate": "cubicOut",
"animationDelayUpdate": 0,
"color": [
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
"#f05b72",
"#ef5b9c",
"#f47920",
"#905a3d",
"#fab27b",
"#2a5caa",
"#444693",
"#726930",
"#b2d235",
"#6d8346",
"#ac6767",
"#1d953f",
"#6950a1",
"#918597"
],
"series": [
{
"type": "bar",
"name": "GDP",
"legendHoverLink": true,
"data": [
30,
20,
10
],
"showBackground": false,
"barMinHeight": 0,
"barCategoryGap": "20%",
"barGap": "30%",
"large": false,
"largeThreshold": 400,
"seriesLayoutBy": "column",
"datasetIndex": 0,
"clip": true,
"zlevel": 0,
"z": 2,
"label": {
"show": true,
"position": "right",
"margin": 8
}
}
],
"legend": [
{
"data": [
"GDP"
],
"selected": {
"GDP": true
}
}
],
"tooltip": {
"show": true,
"trigger": "item",
"triggerOn": "mousemove|click",
"axisPointer": {
"type": "line"
},
"showContent": true,
"alwaysShowContent": false,
"showDelay": 0,
"hideDelay": 100,
"textStyle": {
"fontSize": 14
},
"borderWidth": 0,
"padding": 5
},
"xAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
}
}
],
"yAxis": [
{
"show": true,
"scale": false,
"nameLocation": "end",
"nameGap": 15,
"gridIndex": 0,
"inverse": false,
"offset": 0,
"splitNumber": 5,
"minInterval": 0,
"splitLine": {
"show": false,
"lineStyle": {
"show": true,
"width": 1,
"opacity": 1,
"curveness": 0,
"type": "solid"
}
},
"data": [
"\u4e2d\u56fd",
"\u7f8e\u56fd",
"\u82f1\u56fd"
]
}
]
};
chart_0182a594b6314cb395f04c7eabd37276.setOption(option_0182a594b6314cb395f04c7eabd37276);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/maps/henan.js"></script>
</head>
<body>
<div id="893f45058ae7414f905b9e040a2c86ca" class="chart-container" style="width:900px; height:500px;"></div>
<script>
var chart_893f45058ae7414f905b9e040a2c86ca = echarts.init(
document.getElementById('893f45058ae7414f905b9e040a2c86ca'), 'white', {renderer: 'canvas'});
var option_893f45058ae7414f905b9e040a2c86ca = {
"animation": true,
"animationThreshold": 2000,
"animationDuration": 1000,
"animationEasing": "cubicOut",
"animationDelay": 0,
"animationDurationUpdate": 300,
"animationEasingUpdate": "cubicOut",
"animationDelayUpdate": 0,
"color": [
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
"#f05b72",
"#ef5b9c",
"#f47920",
"#905a3d",
"#fab27b",
"#2a5caa",
"#444693",
"#726930",
"#b2d235",
"#6d8346",
"#ac6767",
"#1d953f",
"#6950a1",
"#918597"
],
"series": [
{
"type": "map",
"name": "\u6cb3\u5357\u7701\u75ab\u60c5\u5206\u5e03",
"label": {
"show": true,
"position": "top",
"margin": 8
},
"mapType": "\u6cb3\u5357",
"data": [
{
"name": "\u90d1\u5dde\u5e02",
"value": 295
},
{
"name": "\u5883\u5916\u8f93\u5165\u5e02",
"value": 79
},
{
"name": "\u5546\u4e18\u5e02",
"value": 106
},
{
"name": "\u5f00\u5c01\u5e02",
"value": 33
},
{
"name": "\u9a7b\u9a6c\u5e97\u5e02",
"value": 143
},
{
"name": "\u5b89\u9633\u5e02",
"value": 54
},
{
"name": "\u8bb8\u660c\u5e02",
"value": 40
},
{
"name": "\u4e09\u95e8\u5ce1\u5e02",
"value": 7
},
{
"name": "\u6f2f\u6cb3\u5e02",
"value": 36
},
{
"name": "\u5468\u53e3\u5e02",
"value": 76
},
{
"name": "\u5357\u9633\u5e02",
"value": 156
},
{
"name": "\u4fe1\u9633\u5e02",
"value": 274
},
{
"name": "\u6d4e\u6e90\u793a\u8303\u533a\u5e02",
"value": 5
},
{
"name": "\u65b0\u4e61\u5e02",
"value": 57
},
{
"name": "\u7126\u4f5c\u5e02",
"value": 32
},
{
"name": "\u5e73\u9876\u5c71\u5e02",
"value": 58
},
{
"name": "\u6d1b\u9633\u5e02",
"value": 31
},
{
"name": "\u6fee\u9633\u5e02",
"value": 17
},
{
"name": "\u9e64\u58c1\u5e02",
"value": 19
},
{
"name": "\u5730\u533a\u5f85\u786e\u8ba4\u5e02",
"value": 0
},
{
"name": "\u6d4e\u6e90\u5e02",
"value": 5
}
],
"roam": true,
"aspectScale": 0.75,
"nameProperty": "name",
"selectedMode": false,
"zoom": 1,
"mapValueCalculation": "sum",
"showLegendSymbol": true,
"emphasis": {}
}
],
"legend": [
{
"data": [
"\u6cb3\u5357\u7701\u75ab\u60c5\u5206\u5e03"
],
"selected": {
"\u6cb3\u5357\u7701\u75ab\u60c5\u5206\u5e03": true
},
"show": true,
"padding": 5,
"itemGap": 10,
"itemWidth": 25,
"itemHeight": 14
}
],
"tooltip": {
"show": true,
"trigger": "item",
"triggerOn": "mousemove|click",
"axisPointer": {
"type": "line"
},
"showContent": true,
"alwaysShowContent": false,
"showDelay": 0,
"hideDelay": 100,
"textStyle": {
"fontSize": 14
},
"borderWidth": 0,
"padding": 5
},
"title": [
{
"text": "\u6cb3\u5357\u7701\u75ab\u60c5\u5730\u56fe",
"padding": 5,
"itemGap": 10
}
],
"visualMap": {
"show": true,
"type": "piecewise",
"min": 0,
"max": 100,
"inRange": {
"color": [
"#50a3ba",
"#eac763",
"#d94e5d"
]
},
"calculable": true,
"inverse": false,
"splitNumber": 5,
"orient": "vertical",
"showLabel": true,
"itemWidth": 20,
"itemHeight": 14,
"borderWidth": 0,
"pieces": [
{
"min": 1,
"max": 99,
"lable": "1~99\u4eba",
"color": "#CCFFFF"
},
{
"min": 100,
"max": 999,
"lable": "100~9999\u4eba",
"color": "#FFFF99"
},
{
"min": 1000,
"max": 4999,
"lable": "1000~4999\u4eba",
"color": "#FF9966"
},
{
"min": 5000,
"max": 9999,
"lable": "5000~99999\u4eba",
"color": "#FF6666"
},
{
"min": 10000,
"max": 99999,
"lable": "10000~99999\u4eba",
"color": "#CC3333"
},
{
"min": 100000,
"lable": "100000+",
"color": "#990033"
}
]
}
};
chart_893f45058ae7414f905b9e040a2c86ca.setOption(option_893f45058ae7414f905b9e040a2c86ca);
</script>
</body>
</html>
"""
演示面向对象类中的成员方法定义和使用
"""
# 定义一个带有成员方法的类
class Student:
name = None # 学生的姓名
def say_hi(self):
print(f"大家好呀,我是{self.name},欢迎大家多多关照")
def say_hi2(self, msg):
print(f"大家好,我是:{self.name}{msg}")
stu = Student()
stu.name = "周杰轮"
stu.say_hi2("哎哟不错哟")
stu2 = Student()
stu2.name = "林俊节"
stu2.say_hi2("小伙子我看好你")
"""
演示类和对象的关系,即面向对象的编程套路(思想)
"""
# 设计一个闹钟类
class Clock:
id = None # 序列化
price = None # 价格
def ring(self):
import winsound
winsound.Beep(2000, 3000)
# 构建2个闹钟对象并让其工作
clock1 = Clock()
clock1.id = "003032"
clock1.price = 19.99
print(f"闹钟ID:{clock1.id},价格:{clock1.price}")
# clock1.ring()
clock2 = Clock()
clock2.id = "003033"
clock2.price = 21.99
print(f"闹钟ID:{clock2.id},价格:{clock2.price}")
clock2.ring()
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册