回到本系列的目录

1. 变量 ❎

变量是用于存储值(字符串、整数、浮点数、布尔值)的容器。

变量的行为就像它包含的值一样。

# 字符串
first_name = "Bro"
food = "pizza"
email = "Bro123@gmail.com"

print(f"你好 {first_name}")
print(f"你喜欢 {food}")
print(f"你的邮箱是: {email}")
# 整数
age = 25
quantity = 3
num_of_students =30

print(f"你 {age} 岁了")
print(f"你购买了 {quantity} 件商品")
print(f"你的班级有 {num_of_students} 名学生")
# 浮点数
price = 10.99
gpa = 3.2
distance = 5.5

print(f"价格是 ${price}")
print(f"你的 GPA 是: {gpa}")
print(f"你跑了 {distance} 公里")
# 布尔值
is_student = False
for_sale = False
is_online = True

if is_online:
    print("你在线")
else:
    print("你离线")

变量赋值

user_name = "Yuuniji"
year = 2025
pi = 3.14
is_admin = True

print(f"用户名: {user_name}")
print(f"当前年份: {year}")
# 四舍五入到两位小数
print(f"Pi: {pi:.2f}")  
# 将布尔值转换为 '是' 或 '否'
print(f"管理员状态: {'是' if is_admin else '否'}") 

2. 类型转换 💱

类型转换是将变量从一种数据类型转换为另一种数据类型的过程。

str(), int(), float(), bool()

name = "Yuuniji"
age = 25
gpa = 3.2
is_student = True
# print(type(name))

gpa = int(gpa) # 3
age = float(age) # 25.0

age = str(age)
age += "1" # "251"

name = bool(name) # True

3. 用户输入 ⌨️

一个提示用户输入数据的函数。

返回输入的数据作为字符串。

name = input("你叫什么名字?: ")
age = int(input("你多大了?: "))
# age = int(age)
age = age + 1

print(f"你好 {name}!")
print("生日快乐")
print(f"你 {age} 岁了")

练习 1 矩形面积计算

length = float(intput("输入长度: "))
width = float(intput("输入宽度: "))
area = length * width

print(f"面积是: {area}cm²")
#Mac 上标 2: Command + Control + Space, 在搜索栏中输入“superscript”或“2”。或者 Option + v

练习 2 购物车程序

item = input("你想买什么商品?: ")
price = float(input("价格是多少?: "))
quantity = int(input("你想买多少?: "))
total = price * quantity

print(f"你购买了 {quantity}{item}")
print(f"总价是: ${total}")

4. ⭐ 填词游戏

填词游戏是一种通过用随机单词填空来创建故事的文字游戏。

adjective1 = input("输入一个形容词(描述): ")
noun1 = input("输入一个名词(人、地点、事物): ")
adjective2 = input("输入一个形容词(描述): ")
verb1 = input("输入一个以 'ing' 结尾的动词")
adjective3 = input("输入一个形容词(描述): ")

print(f"今天我去了一家 {adjective1} 动物园。")
print(f"在一个展区,我看到了一只 {noun1}")
print(f"{noun1}{adjective2} 并且 {verb1}")
print(f"我感到 {adjective3}!")

5. 算术运算符和数学函数 📐

friends = 10

friends = friends + 1
friends += 1
friends = friends - 2
friends -= 2
friends = friends * 3
friends *= 3
friends = friends / 2
friends /= 2
friends = friends ** 2
friends **= 2
remainder = friends % 3
x = 3.14
y = 4
z = 5

result = round(x) # 3
result = abs(y) # 4
result = pow(4, 3) # 4*4*4=64
result = max(x, y, z) # 5
result = min(x, y, z) # 3.14
import math

x = 9
y = 9.1
z = 9.9

print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
result = math.sqrt(x) # 3.0
result = math.ceil(y) # 10
result = math.floor(z) # 9
# C = 2πr
import math

radius = float(input('输入圆的半径: ')) # 10.5

circumference = 2 * math.pi *radius

print(f"周长是: {round(circumference, 2)}cm") # 65.97
# A = πr²
import math

radius = float(input('输入圆的半径: ')) # 10.5

area = math.pi * pow(radius, 2)

print(f"圆的面积是: {round(area, 2)}cm²") # 346.36
# c = √(a²+b²)

import math

a = float(input("输入边 A: ")) # 3
b = float(input("输入边 B: ")) # 4

c = math.sqrt(pow(a, 2) + pow(b, 2))

print(f"边 C = {c}") # 5.0

6. if 语句 🤔

仅在某个条件为真时执行某些代码

否则执行其他操作

age = int(input("请输入您的年龄: "))

if age >= 100:
    print("您年龄太大,无法注册")
elif age >= 18:
    print("您已成功注册!")
elif age < 0:
    print("您还未出生!")
else:
    print("您必须年满18岁才能注册")
response = input("您想要食物吗?(Y/N): ")

if response == "Y":
    print("请享用食物!")
else:
    print("没有食物给您!")
name = input("请输入您的名字: ")

if name == "":
    print("您没有输入名字!")
else:
    print(f"您好 {name}")
for_sale = True

if for_sale:
    print("此商品正在出售")
else:
    print("此商品不在出售")

7. ⭐ 计算器程序 🧮

# + = 加法
# - = 减法
# * = 乘法
# / = 除法

operator = input("请输入运算符 (+ - * /): ")
num1 = float(input("请输入第一个数字: "))
num2 = float(input("请输入第二个数字: "))

if operator == "+":
    result = num1 + num2
    print(round(result, 3))
elif operator == "-":
    result = num1 - num2
    print(round(result, 3))
elif operator == "*":
    result = num1 * num2
    print(round(result, 3))
elif operator == "/":
    result = num1 / num2
    print(round(result, 3))
else:
    print(f"{operator} 不是一个有效的运算符")

8. ⭐ 重量转换程序 🏋️

weight = float(input("请输入您的体重: "))
unit = input("千克还是磅?(K 或 L): ")

if unit == "K":
    weight = weight * 2.205
    unit = "磅"
    print(f"您的体重是: {round(weight, 1)} {unit}")
elif unit == "L":
    weight = weight / 2.205
    unit = "千克"
    print(f"您的体重是: {round(weight, 1)} {unit}")
else:
    print(f"{unit} 不是一个有效的单位")

9. ⭐ 温度转换程序 🌡️

# (°C x 9/5) + 32 = °F
# (°F - 32) x 5/9 = °C
# °(Option + Shift + 8)
unit = input("温度单位是摄氏度还是华氏度?(C/F): ")
temp = float(input("请输入温度: "))

if unit == "C":
    temp = round((9 * temp) / 5 + 32, 1)
    print(f"华氏温度为: {temp}°F")
elif unit == "F":
    temp = round((temp - 32) * 5 / 9, 1)
    print(f"摄氏温度为: {temp}°C")
else:
    print(f"{unit} 不是一个有效的温度单位")

10. 逻辑运算符 🌦️

用于评估多个条件(或、且、非)

or = 至少一个条件必须为真

and = 两个条件都必须为真

not = 反转条件(非假,非真)

temp = 25
is_raining = True

if temp > 35 or temp < 0 or is_raining:
    print("户外活动已取消")
else:
    print("户外活动仍按计划进行")
temp = 25
is_sunny = True

if temp >= 28 and is_sunny:
    print("外面很热 🥵")
    print("天气晴朗 🌞")
elif temp <= 0 and is_sunny:
    print("外面很冷 🥶")
    print("天气晴朗 🌞")
elif 28 > temp > 0 and is_sunny:
    print("外面很温暖 🙂")
    print("天气晴朗 🌞")
elif temp >= 28 and not is_sunny:
    print("外面很热 🥵")
    print("天气多云 ☁️")
elif temp <= 0 and not is_sunny:
    print("外面很冷 🥶")
    print("天气多云 ☁️")
elif 28 > temp > 0 and not is_sunny:
    print("外面很温暖 🙂")
    print("天气多云 ☁️")

11. 条件表达式 ❓

if-else 语句的一行快捷方式(三元运算符)

根据条件打印或分配两个值之一

X if condition else Y

num = 5
a = 6
b = 7
age = 13
temperature = 20
user_role = "guest"

print("正数" if num > 0 else "负数")
result = "偶数" if num % 2 == 0 else "奇数"
max_num = a if a > b else b
min_num = a if a < b else b
status = "成年人" if age >= 18 else "儿童"
weather = "热" if temperature > 20 else "冷"
access_level = "完全访问" if user_role == "admin" else "受限访问"

print(access_level)

12. 字符串方法 〰️

name = input("请输入您的全名:")

result = len(name) 
# yuunijiy -> 8
result = name.find("n") 
# yuunijiy -> 3
result = name.rfind("n") 
# yuunijiy -> 4
name = name.capitalize() 
# yuunijiy -> Yuunijiy
name = name.upper() 
# yuunijiy -> YUUNIJIY
name = name.lower() 
# YUUNIJIY -> yuunijiy
result = name.isdigit() 
# yuunijiy,yuu123 -> False; 123 -> True
result = name.isalpha() 
# yuunijiy -> True; yuu niji,yuu123,123 -> False
phone_number = input("请输入您的电话号码:")

result = phone_number.count("-") 
# 1-234-567-8901 -> 3
phone_number = phone_number.replace("-", " ") 
# 1-234-567-8901 -> 1 234 567 8901

如果你想查看所有可用的字符串方法的完整列表,可以使用帮助函数:print(help(str))

练习:

# 验证用户输入练习
# 1. 用户名不能超过12个字符
# 2. 用户名不能包含空格
# 3. 用户名不能包含数字

username = input("请输入用户名:")

if len(username) > 12:
    print("您的用户名不能超过12个字符")
elif not username.find(" ") == -1:
    print("您的用户名不能包含空格")
elif not username.isalpha():
    print("您的用户名不能包含数字")
else:
    print(f"欢迎 {username}")

13. 字符串索引 ✂️

使用 [] 访问序列中的元素(索引操作符)

[起始 : 结束 : 步长]

credit_number = "1234-5678-9012-3456"

print(credit_number[0]) # 1
print(credit_number[:4]) # 1234
print(credit_number[5:9]) # 5678
print(credit_number[5:]) # 5678-9012-3456
print(credit_number[-1]) # 6
print(credit_number[-2]) # 5
print(credit_number[::2]) # 13-6891-46
print(credit_number[::3]) # 146-136
credit_number = "1234-5678-9012-3456"

last_digits = credit_number[-4:] # 3456
print(f"XXXX-XXXX-XXXX-{last_digits}")
credit_number = "1234-5678-9012-3456"

credit_number = credit_number[::-1]
print(credit_number)
# 6543-2109-8765-4321

14. 格式说明符 💬

{value:flags} 根据插入的标志格式化值

  • .(数字)f = 四舍五入到指定的小数位数(定点数)
  • :(数字) = 分配指定数量的空格
  • :03 = 分配并用零填充指定数量的空格
  • :< = 左对齐
  • :> = 右对齐
  • :^ = 居中对齐
  • :+ = 使用加号表示正值
  • := = 将符号放在最左侧位置
  • : = 在正数前插入空格
  • :, = 逗号分隔符
price1 = 3.14159
price2 = -987.65
price3 = 12.34

print(f"价格 1 是 ${price1:.3f}") # 3.142
print(f"价格 2 是 ${price2:.3f}") # -987.650
print(f"价格 3 是 ${price3:.3f}") # 12.340

print(f"价格 1 是 ${price1:10}") 
print(f"价格 2 是 ${price2:10}") 
print(f"价格 3 是 ${price3:10}") 
# 价格 1 是 $   3.14159
# 价格 2 是 $   -987.65
# 价格 3 是 $     12.34

print(f"价格 1 是 ${price1:010}") 
print(f"价格 2 是 ${price2:010}") 
print(f"价格 3 是 ${price3:010}") 
# 价格 1 是 $0003.14159
# 价格 2 是 $-000987.65
# 价格 3 是 $0000012.34

print(f"价格 1 是 ${price1:<10}") 
print(f"价格 2 是 ${price2:<10}") 
print(f"价格 3 是 ${price3:<10}") 
# 价格 1 是 $3.14159   |
# 价格 2 是 $-987.65   |
# 价格 3 是 $12.34     |

print(f"价格 1 是 ${price1:+}") # +3.14159
print(f"价格 2 是 ${price2:+}") # -987.65
print(f"价格 3 是 ${price3:+}") # +12.34

print(f"价格 1 是 ${price1:10}") 
print(f"价格 2 是 ${price2:10}") 
print(f"价格 3 是 ${price3:10}") 
# 价格 1 是 $ 3.14159
# 价格 2 是 $-987.65
# 价格 3 是 $ 12.34
price1 = 3000.14159
price2 = -9870.65
price3 = 1200.34

print(f"价格 1 是 ${price1:,}") 
print(f"价格 2 是 ${price2:,}") 
print(f"价格 3 是 ${price3:,}") 
# 价格 1 是 $3,000.14159
# 价格 2 是 $-9,870.65
# 价格 3 是 $1,200.34

print(f"价格 1 是 ${price1:+,.2f}") 
print(f"价格 2 是 ${price2:+,.2f}") 
print(f"价格 3 是 ${price3:+,.2f}") 
# 价格 1 是 $+3,000.14
# 价格 2 是 $-9,870.65
# 价格 3 是 $+1,200.34

15. while 循环 ♾️

当某个条件为真时执行一些代码

age = int(input("请输入您的年龄: "))

while age < 0:
    print("年龄不能为负数")
    age = int(input("请输入您的年龄: "))

print(f"您 {age} 岁了")
food = input("输入您喜欢的食物 (q 退出): ")

while not food == "q":
    print(f"您喜欢 {food}")
    food = input("输入您喜欢的另一种食物 (q 退出): ")

print("再见")
num = int(input("输入一个 1 - 10 之间的数字: "))

while num < 1 or num > 10:
    print(f"{num} 无效")
    num = int(input("输入一个 1 - 10 之间的数字: "))

print(f"您的数字是 {num}")

16. ⭐ 复利计算器 💵

# A = P (1 + r/n)ᵗ
# A = 最终金额
# P = 初始本金
# r = 利率
# t = 经过的时间段数

principle = 0
rate = 0
time = 0

while principle <= 0:
    principle = float(input("输入本金金额: "))
    if principle <= 0:
        print("本金不能小于或等于零")

while rate <= 0:
    rate = float(input("输入利率: "))
    if rate <= 0:
        print("利率不能小于或等于零")

while time <= 0:
    time = int(input("输入时间(年): "))
    if time <= 0:
        print("时间不能小于或等于零")

print(principle)
print(rate)
print(time)

total = principle * pow((1 + rate / 100), time)
print(f"{time} 年后的余额: ${total:.2f}")
principle = 0
rate = 0
time = 0

while True:
    principle = float(input("输入本金金额: "))
    if principle < 0:
        print("本金不能小于零")
    else:
        break

while True:
    rate = float(input("输入利率: "))
    if rate < 0:
        print("利率不能小于零")
    else:
        break

while True:
    time = int(input("输入时间(年): "))
    if time < 0:
        print("时间不能小于零")
    else:
        break

total = principle * pow((1 + rate / 100), time)
print(f"{time} 年后的余额: ${total:.2f}")

17. for 循环 🔁

重复执行一段代码固定的次数。

你可以遍历一个范围、字符串、序列等。

for x in range(1, 6):
    print(x) 
# 1
# 2
# 3
# 4
# 5
for x in reversed(range(1, 6)):
    print(x) 

print("HAPPY NEW YEAR!")
# 1 
# 2
# 3
# 4
# 5
# HAPPY NEW YEAR!
for x in range(1, 6, 3):
    print(x) 
# 1
# 4
credit_card = "12-34"
for x in credit_card:
    print(x) 
# 1
# 2
# -
# 3
# 4
for x in range(1, 6):
    if x == 3:
        continue
    else:
        print(x)
# 1
# 2
# 4
# 5
for x in range(1, 6):
    if x == 3:
        break
    else:
        print(x)
# 1
# 2

18. ⭐ 倒计时程序 ⌛

import time

my_time = int(input("请输入时间(秒):")) # 3

for x in range(0, my_time):
    print(x) 
    time.sleep(1)
# 0
# 1
# 2
print("时间到!")
import time

my_time = int(input("请输入时间(秒):")) # 3

for x in range(my_time, 0, -1):
    print(x)
    time.sleep(1)
# 3
# 2
# 1
print("时间到!")
import time

my_time = int(input("请输入时间(秒):")) # 3605

for x in range(my_time, 0, -1):
    seconds = x % 60
    minutes = int(x / 60) % 60
    hours = int(x / 3600)
    print(f"{hours:02}:{minutes:02}:{seconds:02}")
    time.sleep(1)
# 01:00:05
# 01:00:04
# 01:00:03
# 01:00:02
# 01:00:01
# 01:00:00
# 00:59:59
# 00:59:58
print("时间到!")

19. 嵌套循环 ➿

一个循环嵌套在另一个循环中(外层循环,内层循环)

外层循环:
    内层循环:
for x in range(1, 10):
    print(x, end="") 
# 123456789
for x in range(3):
    for y in range(1, 10):
        print(y, end="") 
# 123456789123456789123456789
for x in range(3):
    for y in range(1, 10):
        print(y, end="") 
    print()
# 123456789
# 123456789
# 123456789
rows = int(input("请输入行数:")) # 3 
columns = int(input("请输入列数:")) # 5
symbol = input("请输入要使用的符号:") # *

for x in range(rows):
    for y in range(columns):
        print(symbol, end="") 
    print()
# *****
# *****
# *****

20. 列表、集合和元组 🍎

  • 集合 = 用于存储多个值的单一“变量”
  • 列表 = [] 有序且可更改。允许重复
  • 集合 = {} 无序且不可变,但可以添加/删除元素。不允许重复
  • 元组 = () 有序且不可更改。允许重复。速度更快
fruits = ["苹果", "橙子", "香蕉", "椰子"]

# print(help(fruits))

print(dir(fruits)) 
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',  '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__',  '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',  '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',  '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',  'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

print("苹果" in fruits) # True

print(fruits[0]) # 苹果

print(fruits[0:3]) 
# ["苹果", "橙子", "香蕉"]

print(fruits[::2]) 
# ["苹果", "香蕉"]

print(fruits[::-1]) 
# ["椰子", "香蕉", "橙子", "苹果"]
fruits = ["苹果", "橙子", "香蕉", "椰子"]

fruits.append("菠萝") 
# fruits.remove("菠萝")

print(fruits) 
# ["苹果", "橙子", "香蕉", "椰子", "菠萝"]
fruits = ["苹果", "橙子", "香蕉", "椰子"]

fruits.insert(0, "菠萝") 

print(fruits) 
# ["菠萝", "苹果", "橙子", "香蕉", "椰子"]
fruits = ["苹果", "橙子", "香蕉", "椰子"]

fruits.sort()

print(fruits) 
# ["苹果", "香蕉", "椰子", "橙子"]
fruits = ["苹果", "橙子", "香蕉", "椰子"]

fruits.reverse()

print(fruits) 
# ["椰子", "香蕉", "橙子", "苹果"]
fruits = ["苹果", "橙子", "香蕉", "椰子"]

fruits.sort()
fruits.reverse()

print(fruits) 
# ["橙子", "椰子", "香蕉", "苹果"]
fruits = ["苹果", "橙子", "香蕉", "椰子"]

fruits.clear()

print(fruits) 
# []
fruits = ["苹果", "橙子", "香蕉", "椰子"]

print(fruits.index("苹果")) # 0
fruits = {"苹果", "橙子", "香蕉", "椰子", "椰子"}

print(len(fruits)) # 4

print(dir(fruits)) 
# ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',  '__iand__', '__init__', '__init_subclass__', '__iter__', '__ixor__', '__le__',  '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__',  '__reduce_ex__', '__repr__', '__ror__', '__rxor__', '__setattr__', '__sizeof__',  '__str__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference',  'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint',  'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update',  'union', 'update']

print(fruits[0]) 
# TypeError: 'set' object is not subscriptable

print(fruits)
# {"橙子", "苹果", "香蕉", "椰子"}

fruits.pop()
# {"橙子", "苹果", "香蕉"}
# OR {"苹果", "香蕉", "椰子"}
# OR {"橙子", "香蕉", "椰子"}
# OR ...

fruits.clear() # set()
fruits = ("苹果", "橙子", "香蕉", "椰子", "椰子")

print(dir(fruits)) 
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

print(fruits)
# ("苹果", "橙子", "香蕉", "椰子", "椰子")

21. ⭐ 购物车程序 🛒

foods = []
prices = []
total = 0

while True:
    food = input("请输入要购买的食物(输入q退出):")
    if food.lower() == "q":
        break
    else:
        price = float(input(f"请输入{food}的价格:$"))
        foods.append(food)
        prices.append(price)

print("----- 您的购物车 -----")

for food in foods:
    print(food, end=" ")

for price in prices:
    total += price

print()
print(f"您的总金额是:${total}")

22. 二维集合 ⬜

fruits = ["苹果", "橙子", "香蕉", "椰子"]
vegetables = ["芹菜", "胡萝卜", "土豆"]
meats = ["鸡肉", "鱼", "火鸡"]

groceries = [fruits, vegetables, meats]

print(groceries[0])
# ["苹果", "橙子", "香蕉", "椰子"]

print(groceries[0][3])
# 椰子

print(groceries[2][3])
# IndexError: 列表索引超出范围
groceries = [["苹果", "橙子", "香蕉", "椰子"], 
             ["芹菜", "胡萝卜", "土豆"], 
             ["鸡肉", "鱼", "火鸡"]]

for collection in groceries:
    for food in collection:
        print(food, end=" ")
    print()
# 苹果 橙子 香蕉 椰子
# 芹菜 胡萝卜 土豆
# 鸡肉 鱼 火鸡
num_pad = ((1, 2, 3),
           (4, 5, 6),
           (7, 8, 9),
           ("*", 0, "#"))

for row in num_pad:
    for num in row:
        print(num, end=" ")
    print()
# 1 2 3
# 4 5 6
# 7 8 9
# * 0 #

23. ⭐ 问答游戏 💯

questions = ("元素周期表中有多少个元素?:", 
            "哪种动物产的蛋最大?:",
            "地球大气中含量最多的气体是什么?:",
            "人体有多少块骨头?:",
            "太阳系中最热的行星是哪个?:")

options = (("A. 116", "B. 117", "C. 118", "D. 119"),
           ("A. 鲸鱼", "B. 鳄鱼", "C. 大象", "D. 鸵鸟"),
           ("A. 氮气", "B. 氧气", "C. 二氧化碳", "D. 氢气"),
           ("A. 206", "B. 207", "C. 208", "D. 209"),
           ("A. 水星", "B. 金星", "C. 地球", "D. 火星"))

answers = ("C", "D", "A", "A", "B" )
guesses = []
score = 0
question_num = 0

for question in questions:
    print("-----------------------")
    print(question)
    for option in options[question_num]:
        print(option)

    guess = input("输入(A, B, C, D):").upper()
    guesses.append(guess)
    if guess == answers[question_num]:
        score += 1
        print("正确!")
    else:
        print("错误!")
        print(f"正确答案是 {answers[question_num]}")
    question_num += 1

print("-----------------------")
print("          结果          ")
print("-----------------------")

print("答案:", end="")
for answer in answers:
    print(answer, end=" ")
print()

print("猜测:", end="")
for guess in guesses:
    print(guess, end=" ")
print()

score = int(score / len(questions) * 100)
print(f"您的得分是:{score}%")

24. 字典 📙

字典是一个有序且可变的{键:值}对集合。不允许重复。

capitals = {"USA": "Washington D.C.",
            "India": "New Delhi",
            "China": "Beijing",
            "Russia": "Moscow"}

print(dir(capitals))
# print(help(capitals))
# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

print(capitals.get("USA")) # Washington D.C.
print(capitals.get("Japan")) # None

capitals.update({"Germany": "Berlin"})
capitals.update({"USA": "Detroit"})
# {"USA": "Detroit", "India": "New Delhi", "China": "Beijing", "Russia": "Moscow", "Germany": "Berlin"}

capitals.pop("China")
# {"USA": "Detroit", "India": "New Delhi", "Russia": "Moscow", "Germany": "Berlin"}

capitals.popitem()
# {"USA": "Detroit", "India": "New Delhi", "Russia": "Moscow"}

# capitals.clear()
# {}

keys = capitals.keys()
# dict_keys(['USA', 'India', 'Russia'])
for keys in capitals.keys():
    print(key)
# USA
# India
# Russia

values = capitals.values()
# dict_values(['Detroit', 'New Delhi', 'Moscow'])
for value in capitals.values():
    print(value)
# Detroit
# New Delhi
# Moscow

items = capitals.items()
print(items)
# dict_items([('USA', 'Detroit'), ('India', 'New Delhi'), ('Russia', 'Moscow')])

for key, value in capitals.items():
    print(f"{key}: {value}")
# USA: Detroit
# India: New Delhi
# Russia: Moscow

25. ⭐ 小吃摊程序 🍿

menu = {"pizza": 3.00,         # 披萨
        "nachos": 4.50,        # 玉米片
        "popcorn": 6.00,       # 爆米花
        "fries": 2.50,         # 薯条
        "chips": 1.00,         # 薯片
        "pretzel": 3.50,       # 椒盐卷饼
        "soda": 3.00,          # 汽水
        "lemonade": 4.25}      # 柠檬水
cart = []
total = 0

print("----- 菜单 -----")
for key, value in menu.items():
    print(f"{key:10}: ${value:.2f}")
print("----------------")

while True:
    food = input("选择一项商品(输入 q 退出):").lower()
    if food == "q":
        break
    elif menu.get(food) is not None:
        cart.append(food)

print("-- 您的订单 --")
for food in cart:
    total += menu.get(food)
    print(food, end=" ")

print()
print(f"总金额为: ${total:.2f}")

26. 随机数 🎲

import random

# print(help random)     # 查看 random 模块的帮助文档

low = 1
high = 100
options = ("rock", "paper", "scissors")  # 石头、剪刀、布
cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]  # 扑克牌

# number = random.randint(1, 6)          # 生成 1 到 6 之间的整数
# number = random.randint(low, high)    # 生成 low 到 high 之间的整数
# number = random.random()              # 生成 0 到 1 之间的随机浮点数
# option = random.choice(options)       # 随机选择一项
# random.shuffle(cards)                 # 洗牌

27. ⭐ 猜数字游戏 🔢

import random

lowest_num = 1
highest_num = 100
answer = random.randint(lowest_num, highest_num)
guesses = 0
is_running = True

print("Python 猜数字游戏")
print(f"请选择一个 {lowest_num}{highest_num} 之间的数字")

while is_running:

    guess = input("请输入你的猜测:")

    if guess.isdigit():
        guess = int(guess)
        guesses += 1

        if guess < lowest_num or guess > highest_num:
            print("这个数字超出了范围")
            print(f"请选择一个 {lowest_num}{highest_num} 之间的数字")
        elif guess < answer:
            print("太小了!再试一次!")
        elif guess > answer:
            print("太大了!再试一次!")
        else:
            print(f"正确!答案就是 {answer}")
            print(f"猜了 {guesses} 次")
            is_running = False
    else:
        print("输入无效")
        print(f"请选择一个 {lowest_num}{highest_num} 之间的数字")

28. ⭐ 石头剪刀布游戏 🗿

import random

options = ("rock", "paper", "scissors") 
playing = True

while playing:

    player = None
    computer = random.choice(options)

    while player not in options:
        player = input("请输入选择(石头、纸、剪刀):")

    print(f"玩家: {player}")
    print(f"电脑: {computer}")

    if player == computer:
        print("平局!")
    elif player == "rock" and computer == "scissors":
        print("你赢了!")
    elif player == "paper" and computer == "rock":
        print("你赢了!")
    elif player == "scissors" and computer == "paper":
        print("你赢了!")
    else:
        print("你输了!")

    play_again = input("再玩一局?(y/n):").lower()
    if not play_again == "y":
        playing = False

print("感谢游玩!")

29. ⭐ 骰子滚动程序 ⚂

import random

print("\u25CF \u250C \u2500 \u2510 \u2502 \u2514 \u2518")
# ● ┌ ─ ┐ │ └ ┘
"┌─────────┐"
"│         │"
"│         │"
"│         │"
"└─────────┘"

dice_art = {
    1: ("┌─────────┐", 
        "│         │", 
        "│    ●    │", 
        "│         │", 
        "└─────────┘"),
    2: ("┌─────────┐", 
        "│  ●      │", 
        "│         │", 
        "│      ●  │", 
        "└─────────┘"),
    3: ("┌─────────┐", 
        "│  ●      │", 
        "│    ●    │", 
        "│      ●  │", 
        "└─────────┘"),
    4: ("┌─────────┐", 
        "│  ●   ●  │", 
        "│         │", 
        "│  ●   ●  │", 
        "└─────────┘"),
    5: ("┌─────────┐", 
        "│  ●   ●  │", 
        "│    ●    │", 
        "│  ●   ●  │", 
        "└─────────┘"),
    6: ("┌─────────┐", 
        "│  ●   ●  │", 
        "│  ●   ●  │", 
        "│  ●   ●  │", 
        "└─────────┘"),
}

dice = []
total = 0
num_of_dice = int(input("请输入骰子数量:"))

for die in range(num_of_dice):
    dice.append(random.randint(1, 6))
print(dice)

# for die in range(num_of_dice):
#     for line in dice_art.get(dice[die]):
#         print(line)

for line in range(5):  # 外部循环,按行打印
    for die in dice:  # 内部循环,遍历每个骰子的点数
        print(dice_art.get(die)[line], end="")  # 打印当前骰子图案的当前行
    print()  # 每打印完一行后换行


for die in dice:
    total += die
print(f"总和: {total}")

30. 函数 📞

# 函数 = 一段可重用的代码块
#        在函数名后加 () 来调用它

def happy_birthday(name, age):
    print(f"祝 {name} 生日快乐!")
    print(f"你今年 {age} 岁!")
    print("祝你生日快乐!")
    print()

happy_birthday("Bro", 20)
happy_birthday("Steve", 30)
happy_birthday("Joe", 40)

--------

def display_invoice(username, amount, due_date):
    print(f"你好 {username}")
    print(f"你的账单金额 ${amount:.2f} 将于 {due_date} 到期")

display_invoice("YuuNiji", 100.01, "01/02")

--------

# return = 用于结束函数并将结果返回给调用者

def add(x, y):
    z = x + y
    return z

def subtract(x, y):
    z = x - y
    return z

def multiply(x, y):
    z = x * y
    return z

def divide(x, y):
    z = x / y
    return z

print(add(1, 2)) # 3
print(subtract(1, 2)) # -1
print(multiply(1, 2)) # 2
print(divide(1, 2)) # 0.5

--------

def create_name(first, last):
    first = first.capitalize()
    last = last.capitalize()
    return first + " " + last

full_name = create_name("yuuniji", "code")

print(full_name) # Yuuniji Code

31. 默认参数 👍

# 默认参数 = 为某些参数设置默认值
#            当省略该参数时使用默认值
#            使函数更灵活,减少参数数量
#            1. 位置参数 2. 默认参数 3. 关键字参数 4. 任意参数

def net_price(list_price, discount=1, tax=0.05):
    return list_price * (1 - discount) * (1 + tax)

print(net_price(500)) # 525.0
print(net_price(500, 0.1)) # 472.5
print(net_price(500, 0.1, 0)) # 450

--------

import time

def count(start, end):
    for x in range(start, end+1):
        print(x)
        time.sleep(1)
    print("完成!")

count(0, 10)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 完成!

--------

import time

def count(start=0, end):
    for x in range(start, end+1):
        print(x)
        time.sleep(1)
    print("完成!")

count(10)
# SyntaxError: 非默认参数不能在默认参数之后

--------

import time

def count(end, start=0):
    for x in range(start, end+1):
        print(x)
        time.sleep(1)
    print("完成!")

count(10)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 完成!

--------

import time

def count(end, start=0):
    for x in range(start, end+1):
        print(x)
        time.sleep(1)
    print("完成!")

count(30, 15)
# 15
# 16
# 17
# 18
# 19
# 20
# 21
# 22
# 23
# 24
# 25
# 26
# 27
# 28
# 29
# 30
# 完成!

32. 关键字参数 🗝️

# 关键字参数 = 在参数前加标识符的参数
#              有助于提高代码可读性
#              参数顺序无关紧要
#              1. 位置参数 2. 默认参数 3. 关键字参数 4. 任意参数

def hello(greeting, title, first, last):
    print(f"{greeting} {title}{first} {last}")

hello("你好", "先生", "海绵宝宝", "方裤")
# 你好 先生海绵宝宝 方裤
hello("你好", "海绵宝宝", "方裤", "先生")
# 你好 海绵宝宝方裤 先生
hello("你好", title="先生", first="海绵宝宝", last="方裤")
# 你好 先生海绵宝宝 方裤
hello("你好", title="先生", last="方裤", first="海绵宝宝")
# 你好 先生海绵宝宝 方裤
hello(title="先生", last="方裤", first="海绵宝宝", "你好")
# SyntaxError: 位置参数不能在关键字参数之后

hello("你好", "先生", "John", "James")
# 你好 先生John James
hello("你好", title="先生", last="John", first="James")
# 你好 先生James John

--------

for x in range(1, 11):
    print(x, end=" ")
    # 1 2 3 4 5 6 7 8 9 10

--------

print("1", "2", "3", "4", "5", sep="-")
# 1-2-3-4-5

--------

def get_phone(country, area, first, last):
    return f"{country}-{area}-{first}-{last}"

phone_num = get_phone(country=1, area=123, first=456, last=7890)

print(phone_num)
# 1-123-456-7890

33. *args 和 **kwargs 📦

# *args    = 允许传递多个非关键字参数
# **kwargs = 允许传递多个关键字参数
#            * 解包操作符
#            1. 位置参数 2. 默认参数 3. 关键字参数 4. 任意参数

def add(a, b):
    return a + b

print(add(1, 2)) # 3
print(add(1, 2, 3))
# TypeError: add() 需要 2 个位置参数,但给定了 3 个

--------

def add(*args):
    print(type(args)) # <class 'tuple'>
    total = 0
    for arg in args:
        total += arg
    return total

print(add(1, 2, 3, 4, 5)) # 15

--------

def display_name(*args):
    for arg in args:
        print(arg, end=" ")

display_name("博士", "海绵宝宝", "Harold", "方裤")
# 博士 海绵宝宝 Harold 方裤

--------

def print_address(**kwargs):
    print(type(kwargs)) # <class 'dict'>
    for value in kwargs.values():
        print(value)

print_address(street="123 Fake St.", 
              city="底特律", 
              state="MI", 
              zip="54321")
# 123 Fake St.
# 底特律
# MI
# 54321

--------

def print_address(**kwargs):
    print(type(kwargs)) # <class 'dict'>
    for key in kwargs.keys():
        print(key)

print_address(street="123 Fake St.", 
              city="底特律", 
              state="MI", 
              zip="54321")
# street
# city
# state
# zip

--------

def print_address(**kwargs):
    print(type(kwargs)) # <class 'dict'>
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_address(street="123 Fake St.", 
              city="底特律", 
              state="MI", 
              zip="54321")
# street: 123 Fake St.
# city: 底特律
# state: MI
# zip: 54321

--------

def shipping_label(*args, **kwargs):
    for arg in args:
        print(arg, end=" ")
    print()

    for value in kwargs.values():
        print(value, end=" ")

shipping_label("博士", "海绵宝宝", "方裤", "III",
               street="123 Fake St.",
               apt="100",
               city="底特律",
               state="MI",
               zip="54321")
# 博士 海绵宝宝 方裤 III
# 123 Fake St. 100 底特律 MI 54321

--------

def shipping_label(*args, **kwargs):
    for arg in args:
        print(arg, end=" ")
    print()

    print(f"{kwargs.get('street')} {kwargs.get('apt')}")
    print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")

shipping_label("博士", "海绵宝宝", "方裤",
               street="123 Fake St.",
               apt="#100",
               city="底特律",
               state="MI",
               zip="54321")
# 博士 海绵宝宝 方裤
# 123 Fake St. #100
# 底特律 MI 54321

--------

def shipping_label(*args, **kwargs):
    for arg in args:
        print(arg, end=" ")
    print()

    print(f"{kwargs.get('street')} {kwargs.get('apt')}")
    print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")

shipping_label("博士", "海绵宝宝", "方裤",
               street="123 Fake St.",
               city="底特律",
               state="MI",
               zip="54321")
# 博士 海绵宝宝 方裤
# 123 Fake St. None
# 底特律 MI 54321

--------

def shipping_label(*args, **kwargs):
    for arg in args:
        print(arg, end=" ")
    print()

    if "apt" in kwargs:
        print(f"{kwargs.get('street')} {kwargs.get('apt')}")
    elif "pobox" in kwargs:
        print(f"{kwargs.get('street')}")
        print(f"{kwargs.get('pobox')}")
    else:
        print(f"{kwargs.get('street')}")

    print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")

shipping_label("博士", "海绵宝宝", "方裤",
               street="123 Fake St.",
               pobox="PO box #1001",
               city="底特律",
               state="MI",
               zip="54321")
# 博士 海绵宝宝 方裤
# 123 Fake St.
# PO box #1001
# 底特律 MI 54321

34. 可迭代对象 🔂

# 可迭代对象 = 一个可以逐一返回其元素的对象/集合,
#               允许在循环中进行迭代

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)
# 1
# 2
# 3
# 4
# 5
numbers = [1, 2, 3, 4, 5]

for number in reversed(numbers):
    print(number)
# 5
# 4
# 3
# 2
# 1
numbers = [1, 2, 3, 4, 5]

for number in reversed(numbers):
    print(number, end=" ")
# 5 4 3 2 1
numbers = [1, 2, 3, 4, 5]

for number in reversed(numbers):
    print(number, end="-")
# 5-4-3-2-1-
numbers = [1, 2, 3, 4, 5]

for number in reversed(numbers):
    print(number, end=" - ")
# 5 - 4 - 3 - 2 - 1 -
numbers = (1, 2, 3, 4, 5)

for number in numbers:
    print(number)
# 1
# 2
# 3
# 4
# 5
fruits = {"apple", "orange", "banana", "coconut"}

for fruit in fruits:
    print(fruit)
# apple
# orange
# banana
# coconut
fruits = {"apple", "orange", "banana", "coconut"}

for fruit in reversed(fruits):
    print(fruit)
# TypeError: 'set' 对象不可反转
name ="Yuu Niji"

for character in name:
    print(character)
# Y
# u
# u
#  
# N
# i
# j
# i
name ="Yuu Niji"

for character in name:
    print(character, end=" ")
# Y u u  N i j i
my_dictionary = {"A": 1, "B": 2, "C": 3}

for key in my_dictionary:
    print(key)
# A
# B
# C
my_dictionary = {"A": 1, "B": 2, "C": 3}

for value in my_dictionary.values():
    print(value)
# 1
# 2
# 3
my_dictionary = {"A": 1, "B": 2, "C": 3}

for key, value in my_dictionary.items():
    print(key, value)
# A 1
# B 2
# C 3
my_dictionary = {"A": 1, "B": 2, "C": 3}

for key, value in my_dictionary.items():
    print(f"{key} = {value}")
# A = 1
# B = 2
# C = 3

35. 成员运算符 🔎

# 成员运算符 = 用于测试一个值或变量是否出现在一个序列中
#                (字符串、列表、元组、集合或字典)
#                1. in
#                2. not in

word = "APPLE"

letter = input("猜一个秘密单词中的字母:")

if letter in word:
    print(f"存在字母 {letter}")
else:
    print(f"未找到字母 {letter}")
# 猜一个秘密单词中的字母:A
# 存在字母 A
# 猜一个秘密单词中的字母:Z
# 未找到字母 Z
word = "APPLE"

letter = input("猜一个秘密单词中的字母:")

if letter not in word:
    print(f"未找到字母 {letter}")
else:
    print(f"存在字母 {letter}")
# 猜一个秘密单词中的字母:E
# 存在字母 E
# 猜一个秘密单词中的字母:Q
# 未找到字母 Q
students = {"Spongbob", "Patrick", "Sandy"}

student = input("输入一个学生姓名:")

if student in students:
    print(f"{student} 是学生")
else:
    print(f"未找到学生 {student}")
# 输入一个学生姓名:Spongbob
# Spongbob 是学生
# 输入一个学生姓名:Yuuniji
# 未找到学生 Yuuniji
students = {"Spongbob", "Patrick", "Sandy"}

student = input("输入一个学生姓名:")

if student not in students:
    print(f"未找到学生 {student}")
else:
    print(f"{student} 是学生")
# 输入一个学生姓名:Sandy
# Sandy 是学生
# 输入一个学生姓名:Github
# 未找到学生 Github
grades = {"Sandy": "A", 
          "Squidward": "B", 
          "Spongbob": "C", 
          "Patrick": "D"}

student = input("输入一个学生姓名:")

if student in grades:
    print(f"{student} 的成绩是 {grades[student]}")
else:
    print(f"未找到学生 {student}")
# 输入一个学生姓名:Spongbob
# Spongbob 的成绩是 C
# 输入一个学生姓名:Sandy
# Sandy 的成绩是 A
# 输入一个学生姓名:Squidward
# Squidward 的成绩是 B
# 输入一个学生姓名:Patrick
# Patrick 的成绩是 D
# 输入一个学生姓名:Yuuniji
# 未找到学生 Yuuniji
email = "yuuniji81@gmail.com"

if "@" in email and "." in email:
    print("有效邮箱")
else:
    print("无效邮箱")
# 有效邮箱
email = "yuuniji81gmail.com"

if "@" in email and "." in email:
    print("有效邮箱")
else:
    print("无效邮箱")
# 无效邮箱
email = "yuuniji81@gmailcom"

if "@" in email and "." in email:
    print("有效邮箱")
else:
    print("无效邮箱")
# 无效邮箱

36. 列表推导 📃

# 列表推导 = Python 中创建列表的一种简洁方式
#             比传统循环更紧凑且易于阅读
#             [表达式 for 值 in 可迭代对象 if 条件]

doubles = []
for x in range(1, 11):
    doubles.append(x * 2)

print(doubles)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
doubles = [x * 2 for x in range(1, 11)]

print(doubles)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
triples = [y * 3 for y in range(1, 11)]

print(triples)
# [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
squares = [z * z for z in range(1, 11)]

print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
fruits = ["apple", "orange", "banana", "coconut"]
fruits = [fruit.upper() for fruit in fruits]
print(fruits)
# ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
fruits = [fruit.upper() for fruit in ["apple", "orange", "banana", "coconut"]]

print(fruits)
# ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
fruits = ["apple", "orange", "banana", "coconut"]
fruit_chars = [fruit[0] for fruit in fruits]
print(fruit_chars)
# ['a', 'o', 'b', 'c']
numbers = [1, -2, 3, -4, 5, -6, 8, -7]
positive_nums = [num for num in numbers if num >= 0]
negative_nums = [num for num in numbers if num < 0]
even_nums = [num for num in numbers if num % 2 == 0]
odd_nums = [num for num in numbers if num % 2 == 1]

print(positive_nums)
# [1, 3, 5, 8]
print(negative_nums)
# [-2, -4, -6, -7]
print(even_nums)
# [-2, -4, -6, 8]
print(odd_nums)
# [1, 3, 5, -7]
grades = [85, 42, 79, 90, 56, 61, 30]
passing_grades = [grade for grade in grades if grade >= 60]

print(passing_grades)
# [85, 79, 90, 61]

37. match-case 语句 📆

# match-case 语句(类似 switch):代替多个 'elif' 语句的另一种方式
#                                当值匹配某个 'case' 时执行相应代码
#                                优点:代码更简洁,语法更易读

def day_of_week(day):
    if day == 1:
        return "今天是星期日"
    elif day == 2:
        return "今天是星期一"
    elif day == 3:
        return "今天是星期二"
    elif day == 4:
        return "今天是星期三"
    elif day == 5:
        return "今天是星期四"
    elif day == 6:
        return "今天是星期五"
    elif day == 7:
        return "今天是星期六"
    else:
        return "不是有效的日期"

print(day_of_week(1))
# 今天是星期日
def day_of_week(day):
    match day:
        case 1:
            return "今天是星期日"
        case 2:
            return "今天是星期一"
        case 3:
            return "今天是星期二"
        case 4:
            return "今天是星期三"
        case 5:
            return "今天是星期四"
        case 6:
            return "今天是星期五"
        case 7:
            return "今天是星期六"
        case _: # _ = 通配符
            return "不是有效的日期"

print(day_of_week(1))
# 今天是星期日
def is_weekend(day):
    match day:
        case "Sunday":
            return True
        case "Monday":
            return False
        case "Tuesday":
            return False
        case "Wednesday":
            return False
        case "Thursday":
            return False
        case "Friday":
            return False
        case "Saturday":
            return True
        case _: # _ = 通配符
            return False

print(is_weekend("Sunday"))
# True
def is_weekend(day):
    match day:
        case "Saturday" | "Sunday": # | = 或
            return True
        case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
            return False
        case _: # _ = 通配符
            return False

print(is_weekend("Sunday"))
# True

38. 模块 📨

# 模块 = 包含你想在程序中使用的代码文件
#        使用 'import' 引入模块(内置或自定义)
#        有助于将大型程序分解为可重用的独立文件

# print(help("modules"))
# print(help("math"))

import math

print(math.pi)
# 3.141592653589794
import math as m

print(math.pi)
# NameError: name 'math' is not defined
import math as m

print(m.pi)
# 3.141592653589794
from math import pi

print(pi)
# 3.141592653589794
from math import e

print(e)
# 2.718281828459045
from math import e

a, b, c, d = 1, 2, 3, 4

print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
# 2.718281828459045
# 7.3890560989306495
# 20.085536923187664
# 54.5915003314423
from math import e

a, b, c, d, e = 1, 2, 3, 4, 5

print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
print(e ** e)
# 2.718281828459045
# 7.3890560989306495
# 20.085536923187664
# 54.5915003314423
# 148.41315910257657
# example.py

pi = 3.14159

def square(x):
    return x ** 2

def cube(x):
    return x ** 3

def circumference(radius):
    return 2 * pi * radius

def area(radius):
    return pi * radius ** 2
# main.py

import example

result = example.pi

print(result)
# 3.14159
import example

result = example.square(3)

print(result)  # 9
import example

result = example.cube(3)

print(result)
# 27
import example

result = example.circumference(3)

print(result)
# 18.849539999999998
import example

result = example.area(3)

print(result)
# 28.27431

39. 作用域解析 🔬

# 变量作用域 = 变量可见和可访问的范围
# 作用域解析 = (LEGB) 局部 -> 闭包 -> 全局 -> 内置

def func1():
    a = 1
    print(a)

def func2():
    b = 2
    print(b)

func1() # 1
func2() # 2
def func1():
    a = 1
    print(b)

def func2():
    b = 2
    print(a)

func1()
func2()
# NameError: 名称 'b' 未定义
def happy_birthday(name, age):
    print(f"亲爱的 {name},生日快乐")
    print(f"你今年 {age} 岁")

def main():
    name = "Yuuniji"
    age = 21
    happy_birthday(name, age)
main()
def func1():
    x = 1
    print(x)

def func2():
    x = 2
    print(x)

func1() # 1
func2() # 2
def func1():
    x = 1

    def func2():
        x = 2
        print(x)
    func2()

func1()
# 2
def func1():
    x = 1

    def func2():
        print(x)
    func2()

func1()
# 1
def func1():
    print(x)

def func2():
    print(x)

x = 3

func1() # 3
func2() # 3
def func1():
    x = 1
    print(x)

def func2():
    x = 2
    print(x)

x = 3

func1() # 1
func2() # 2
from math import e

print(e)
# 2.718281828459045
from math import e

def func1():
    print(e)

func1()
# 2.718281828459045
from math import e

def func1():
    print(e)

e = 3

func1()
# 3

40. if name == ‘main’: 📥

# if __name__ == '__main__': (此脚本可以被导入或独立运行)
# 模块中的函数和类可以被重用,而主代码块不会执行
# 最佳实践(代码模块化,
#         提高可读性,
#         避免全局变量,
#         防止意外执行)

# 示例:library = 导入库以使用功能
#               直接运行库时,显示帮助页面

def main():
    # 你的程序代码在这里

if __name__ == '__main__':
    main()
# script1.py
# print(dir())
print(__name__)
# __main__
# script1.py
from script2 import *
# 当 script2.py 被 script1.py 导入时,它被视为一个模块,而不是主脚本。因此,Python 将其 __name__ 设置为模块名称,即 "script2"(文件名,不含 .py 扩展名)。
# 在 script2.py 中的 print(__name__) 语句会在导入过程中执行,打印 "script2"。
print(__name__)
# script2
# __main__
# script1.py
print(__name__)
# script2
# __main__

--------

# script2.py
from script1 import *

print(__name__)
# script1
# __main__
# script1.py
def favorite_food(food):
    print(f"你最喜欢的食物是 {food}")

def main():
    print("这是 script1")
    favorite_food("披萨")
    print("再见!")

if __name__ == '__main__':
    main()
# 这是 script1
# 你最喜欢的食物是披萨
# 再见!
--------

# script2.py
from script1 import *
# 
# script1.py
def favorite_food(food):
    print(f"你最喜欢的食物是 {food}")

print("这是 script1")
favorite_food("披萨")
print("再见!")

--------

# script2.py
from script1 import *
# 这是 script1
# 你最喜欢的食物是披萨
# 再见!
# script1.py
def favorite_food(food):
    print(f"你最喜欢的食物是 {food}")

def main():
    print("这是 script1")
    favorite_food("披萨")
    print("再见!")

if __name__ == '__main__':
    main()

--------

# script2.py
from script1 import *

def favorite_drink(drink):
    print(f"你最喜欢的饮料是 {drink}")

print("这是 script2")
favorite_food("寿司")
favorite_drink("咖啡")
print("再见!")
# 这是 script2
# 你最喜欢的食物是寿司
# 你最喜欢的饮料是咖啡
# 再见!
# script1.py
def favorite_food(food):
    print(f"你最喜欢的食物是 {food}")

def main():
    print("这是 script1")
    favorite_food("披萨")
    print("再见!")

if __name__ == '__main__':
    main()

--------

# script2.py
from script1 import *

def favorite_drink(drink):
    print(f"你最喜欢的饮料是 {drink}")

def main():
    print("这是 script2")
    favorite_food("寿司")
    favorite_drink("咖啡")
    print("再见!")

if __name__ == '__main__':
    main()
# 这是 script2
# 你最喜欢的食物是寿司
# 你最喜欢的饮料是咖啡
# 再见!

41. ⭐ 银行程序 💰

# Python 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款

def show_balance():
    pass

def deposit():
    pass

def withdraw():
    pass

balance = 0
is_running = True

while is_running:
    print("银行程序")
    print("1. 显示余额")
    print("2. 存款")
    print("3. 取款")
    print("4. 退出")

    choice = input("请输入您的选择 (1-4): ")

    if choice == '1':
        show_balance()
    elif choice == '2':
        deposit()
    elif choice == '3':
        withdraw()
    elif choice == '4':
        is_running = False
    else:
        print("无效的选择")

print("谢谢!祝您有愉快的一天!")
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 4
# 谢谢!祝您有愉快的一天!
def show_balance():
    print(f"您的余额为 ${balance:.2f}")

def deposit():
    amount = float(input("请输入存款金额: "))

    if amount < 0:
        print("无效的金额")
    else:
        return amount

def withdraw():
    pass

balance = 0
is_running = True

while is_running:
    print("银行程序")
    print("1. 显示余额")
    print("2. 存款")
    print("3. 取款")
    print("4. 退出")

    choice = input("请输入您的选择 (1-4): ")

    if choice == '1':
        show_balance()
    elif choice == '2':
        balance += deposit()
    elif choice == '3':
        withdraw()
    elif choice == '4':
        is_running = False
    else:
        print("无效的选择")

print("谢谢!祝您有愉快的一天!")
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 您的余额为 $0.00
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 2
# 请输入存款金额: 100
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 您的余额为 $100.00
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 2
# 请输入存款金额: -420.69
# 无效的金额
# TypeError: 不支持的操作数类型 +=: 'float' 和 'NoneType'
def show_balance():
    print(f"您的余额为 ${balance:.2f}")

def deposit():
    amount = float(input("请输入存款金额: "))

    if amount < 0:
        print("无效的金额")
        return 0
    else:
        return amount

def withdraw():
    pass

balance = 0
is_running = True

while is_running:
    print("银行程序")
    print("1. 显示余额")
    print("2. 存款")
    print("3. 取款")
    print("4. 退出")

    choice = input("请输入您的选择 (1-4): ")

    if choice == '1':
        show_balance()
    elif choice == '2':
        balance += deposit()
    elif choice == '3':
        withdraw()
    elif choice == '4':
        is_running = False
    else:
        print("无效的选择")

print("谢谢!祝您有愉快的一天!")
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 2
# 请输入存款金额: -420.69
# 无效的金额
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 2
# 请输入存款金额: 50.01
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 您的余额为 $50.01
def show_balance():
    print(f"您的余额为 ${balance:.2f}")

def deposit():
    amount = float(input("请输入存款金额: "))

    if amount < 0:
        print("无效的金额")
        return 0
    else:
        return amount

def withdraw():
    amount = float(input("请输入取款金额: "))

    if amount > balance:
        print("余额不足")
        return 0
    elif amount < 0:
        print("金额必须大于0")
        return 0
    else:
        return amount

balance = 0
is_running = True

while is_running:
    print("银行程序")
    print("1. 显示余额")
    print("2. 存款")
    print("3. 取款")
    print("4. 退出")

    choice = input("请输入您的选择 (1-4): ")

    if choice == '1':
        show_balance()
    elif choice == '2':
        balance += deposit()
    elif choice == '3':
        balance -= withdraw()
    elif choice == '4':
        is_running = False
    else:
        print("无效的选择")

print("谢谢!祝您有愉快的一天!")
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 您的余额为 $0.00
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 2
# 请输入存款金额: 100
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 您的余额为 $100.00
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 3
# 请输入取款金额: 1000000000000000000000
# 余额不足
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 3
# 请输入取款金额: -420.69
# 金额必须大于0
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 3
# 请输入取款金额: -49.99
# 金额必须大于0
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 1
# 您的余额为 $50.01
# 银行程序
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# 请输入您的选择 (1-4): 4
# 谢谢!祝您有愉快的一天!
def show_balance(balance):
    print("*********************")
    print(f"您的余额为 ${balance:.2f}")
    print("*********************")

def deposit():
    print("*********************")
    amount = float(input("请输入存款金额: "))
    print("*********************")

    if amount < 0:
        print("*********************")
        print("无效的金额")
        print("*********************")
        return 0
    else:
        return amount

def withdraw(balance):
    print("*********************")
    amount = float(input("请输入取款金额: "))
    print("*********************")

    if amount > balance:
        print("*********************")
        print("余额不足")
        print("*********************")
        return 0
    elif amount < 0:
        print("*********************")
        print("金额必须大于0")
        print("*********************")
        return 0
    else:
        return amount

def main():
    balance = 0
    is_running = True

    while is_running:
        print("*********************")
        print("   银行程序   ")
        print("*********************")
        print("1. 显示余额")
        print("2. 存款")
        print("3. 取款")
        print("4. 退出")
        print("*********************")
        choice = input("请输入您的选择 (1-4): ")

        if choice == '1':
            show_balance(balance)
        elif choice == '2':
            balance += deposit()
        elif choice == '3':
            balance -= withdraw(balance)
        elif choice == '4':
            is_running = False
        else:
            print("*********************")
            print("无效的选择")
            print("*********************")
    print("*********************")
    print("谢谢!祝您有愉快的一天!")
    print("*********************")

if __name__ == '__main__':
    main()
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 1
# *********************
# 您的余额为 $0.00
# *********************
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 2
# *********************
# 请输入存款金额: 100.01
# *********************
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 1
# *********************
# 您的余额为 $100.01
# *********************
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 3
# 请输入取款金额: 1000
# *********************
# 余额不足
# *********************
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 3
# 请输入取款金额: 50
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 1
# *********************
# 您的余额为 $50.01
# *********************
# *********************
#    银行程序   
# *********************
# 1. 显示余额
# 2. 存款
# 3. 取款
# 4. 退出
# *********************
# 请输入您的选择 (1-4): 4
# *********************
# 谢谢!祝您有愉快的一天!
# *********************

42. ⭐ 老虎机 🎰

# Python 老虎机

def spin_row():
    pass

def print_row():
    pass

def get_payout():
    pass

def main():
    pass

if __name__ == '__main__':
    main()
def spin_row():
    pass

def print_row():
    pass

def get_payout():
    pass

def main():
    balance = 100

    print("*************************")
    print("欢迎体验 Python 老虎机")
    print("符号:🍒 🍉 🍋 🔔 ⭐️")
    print("*************************")

    while balance > 0:
        print(f"当前余额:${balance}")

        bet = input("请输入您的下注金额:")

        if not bet.isdigit():
            print("请输入有效的数字")
            continue
        
        bet = int(bet)

        if bet > balance:
            print("余额不足")
            continue

        if bet < 0:
            print("下注金额必须大于 0")
            continue

        balance -= bet

if __name__ == '__main__':
    main()
# *************************
# 欢迎体验 Python 老虎机
# 符号:🍒 🍉 🍋 🔔 ⭐️
# *************************
# 当前余额:$100
# 请输入您的下注金额:pizza
# 请输入有效的数字
# 当前余额:$100
# 请输入您的下注金额:10000000000000000
# 余额不足
# 当前余额:$100
# 请输入您的下注金额:0
# 下注金额必须大于 0
# 当前余额:$100
# 请输入您的下注金额:1
# 当前余额:$99
# 请输入您的下注金额:10
# 当前余额:$89
# 请输入您的下注金额:90
# 余额不足
# 当前余额:$89
# 请输入您的下注金额:89
import random

def spin_row():
    symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']

    # results = []
    # for _ in range(3):
    #     results.append(random.choice(symbols))
    # return results

    return [random.choice(symbols) for _ in range(3)]
    # return [random.choice(symbols) for symbols in range(3)]

def print_row():
    pass

def get_payout():
    pass

def main():
    balance = 100

    print("*************************")
    print("欢迎体验 Python 老虎机")
    print("符号:🍒 🍉 🍋 🔔 ⭐️")
    print("*************************")

    while balance > 0:
        print(f"当前余额:${balance}")

        bet = input("请输入您的下注金额:")

        if not bet.isdigit():
            print("请输入有效的数字")
            continue
        
        bet = int(bet)

        if bet > balance:
            print("余额不足")
            continue

        if bet < 0:
            print("下注金额必须大于 0")
            continue

        balance -= bet

        row = spin_row()
        print(row)

if __name__ == '__main__':
    main()
# *************************
# 欢迎体验 Python 老虎机
# 符号:🍒 🍉 🍋 🔔 ⭐️
# *************************
# 当前余额:$100
# 请输入您的下注金额:1
# ['⭐️', '🍋', '🍋']
# 当前余额:$99
# 请输入您的下注金额:1
# ['🍉', '🍒', '⭐️']
# 当前余额:$98
# 请输入您的下注金额:1
# ['🍒', '🍉', '🍒']
# 当前余额:$97
# 请输入您的下注金额:1
# ['⭐️', '🍋', '⭐️']
# 当前余额:$96
# 请输入您的下注金额:1
# ['🍋', '🍒', '🍋']
# 当前余额:$95
# 请输入您的下注金额:
import random

def spin_row():
    symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']

    # results = []
    # for _ in range(3):
    #     results.append(random.choice(symbols))
    # return results

    return [random.choice(symbols) for _ in range(3)]
    # return [random.choice(symbols) for symbols in range(3)]

def print_row(row):
    print(" ".join(row))

def get_payout():
    pass

def main():
    balance = 100

    print("*************************")
    print("欢迎体验 Python 老虎机")
    print("符号:🍒 🍉 🍋 🔔 ⭐️")
    print("*************************")

    while balance > 0:
        print(f"当前余额:${balance}")

        bet = input("请输入您的下注金额:")

        if not bet.isdigit():
            print("请输入有效的数字")
            continue
        
        bet = int(bet)

        if bet > balance:
            print("余额不足")
            continue

        if bet < 0:
            print("下注金额必须大于 0")
            continue

        balance -= bet

        row = spin_row()
        print("旋转中...\n")
        print_row(row)

if __name__ == '__main__':
    main()
# *************************
# 欢迎体验 Python 老虎机
# 符号:🍒 🍉 🍋 🔔 ⭐️
# *************************
# 当前余额:$100
# 请输入您的下注金额:1
# 旋转中...
#
# 🍋 ⭐️ 🔔
# 当前余额:$99
# 请输入您的下注金额:
import random

def spin_row():
    symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']

    # results = []
    # for _ in range(3):
    #     results.append(random.choice(symbols))
    # return results

    return [random.choice(symbols) for _ in range(3)]
    # return [random.choice(symbols) for symbols in range(3)]

def print_row(row):
    print("*************")
    print(" | ".join(row))
    print("*************")

def get_payout():
    pass

def main():
    balance = 100

    print("*************************")
    print("欢迎体验 Python 老虎机")
    print("符号:🍒 🍉 🍋 🔔 ⭐️")
    print("*************************")

    while balance > 0:
        print(f"当前余额:${balance}")

        bet = input("请输入您的下注金额:")

        if not bet.isdigit():
            print("请输入有效的数字")
            continue
        
        bet = int(bet)

        if bet > balance:
            print("余额不足")
            continue

        if bet < 0:
            print("下注金额必须大于 0")
            continue

        balance -= bet

        row = spin_row()
        print("旋转中...\n")
        print_row(row)

if __name__ == '__main__':
    main()
# *************************
# 欢迎体验 Python 老虎机
# 符号:🍒 🍉 🍋 🔔 ⭐️
# *************************
# 当前余额:$100
# 请输入您的下注金额:1
# 旋转中...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# 当前余额:$99
# 请输入您的下注金额:2
# 旋转中...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# 当前余额:$97
# 请输入您的下注金额:3
# 旋转中...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# 当前余额:$94
# 请输入您的下注金额:4
# 旋转中...
#
# *************
# 🍉 | 🍉 | 🍉
# *************
# 当前余额:$90
# 请输入您的下注金额:
import random

def spin_row():
    symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']

    # results = []
    # for _ in range(3):
    #     results.append(random.choice(symbols))
    # return results

    return [random.choice(symbols) for _ in range(3)]
    # return [random.choice(symbols) for symbols in range(3)]

def print_row(row):
    print("*************")
    print(" | ".join(row))
    print("*************")

def get_payout(row, bet):
    if row[0] == row[1] == row[2]:
        if row[0] == '🍒':
            return bet * 3
        elif row[0] == '🍉':
            return bet * 4
        elif row[0] == '🍋':
            return bet * 5
        elif row[0] == '🔔':
            return bet * 10
        elif row[0] == '⭐️':
            return bet * 20
    return 0

def main():
    balance = 100

    print("*************************")
    print("欢迎体验 Python 老虎机")
    print("符号:🍒 🍉 🍋 🔔 ⭐️")
    print("*************************")

    while balance > 0:
        print(f"当前余额:${balance}")

        bet = input("请输入您的下注金额:")

        if not bet.isdigit():
            print("请输入有效的数字")
            continue
        
        bet = int(bet)

        if bet > balance:
            print("余额不足")
            continue

        if bet < 0:
            print("下注金额必须大于 0")
            continue

        balance -= bet

        row = spin_row()
        print("旋转中...\n")
        print_row(row)

        payout = get_payout(row, bet)

        if payout > 0:
            print(f"您赢得了 ${payout}")
        else:
            print("很遗憾,您本轮未获胜")
        
        balance += payout

if __name__ == '__main__':
    main()
# *************************
# 欢迎体验 Python 老虎机
# 符号:🍒 🍉 🍋 🔔 ⭐️
# *************************
# 当前余额:$100
# 请输入您的下注金额:1
# 旋转中...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# 很遗憾,您本轮未获胜
# 当前余额:$99
# 请输入您的下注金额:2
# 旋转中...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# 很遗憾,您本轮未获胜
# 当前余额:$97
# 请输入您的下注金额:3
# 旋转中...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# 很遗憾,您本轮未获胜
# 当前余额:$94
# 请输入您的下注金额:1
# 旋转中...
#
# *************
# 🍉 | 🍉 | 🍉
# *************
# 您赢得了 $4
# 当前余额:$93
# 请输入您的下注金额:
import random

def spin_row():
    symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']

    # results = []
    # for _ in range(3):
    #     results.append(random.choice(symbols))
    # return results

    return [random.choice(symbols) for _ in range(3)]
    # return [random.choice(symbols) for symbols in range(3)]

def print_row(row):
    print("*************")
    print(" | ".join(row))
    print("*************")

def get_payout(row, bet):
    if row[0] == row[1] == row[2]:
        if row[0] == '🍒':
            return bet * 3
        elif row[0] == '🍉':
            return bet * 4
        elif row[0] == '🍋':
            return bet * 5
        elif row[0] == '🔔':
            return bet * 10
        elif row[0] == '⭐️':
            return bet * 20
    return 0

def main():
    balance = 100

    print("*************************")
    print("欢迎体验 Python 老虎机")
    print("符号:🍒 🍉 🍋 🔔 ⭐️")
    print("*************************")

    while balance > 0:
        print(f"当前余额:${balance}")

        bet = input("请输入您的下注金额:")

        if not bet.isdigit():
            print("请输入有效的数字")
            continue
        
        bet = int(bet)

        if bet > balance:
            print("余额不足")
            continue

        if bet < 0:
            print("下注金额必须大于 0")
            continue

        balance -= bet

        row = spin_row()
        print("旋转中...\n")
        print_row(row)

        payout = get_payout(row, bet)

        if payout > 0:
            print(f"您赢得了 ${payout}")
        else:
            print("很遗憾,您本轮未获胜")
        
        balance += payout

        play_again = input("您想再次旋转吗?(Y/N):").upper()

        if play_again != 'Y':
            break

    print("*******************************************")
    print(f"游戏结束!您的最终余额为 ${balance}")
    print("*******************************************")

if __name__ == '__main__':
    main()
# *************************
# 欢迎体验 Python 老虎机
# 符号:🍒 🍉 🍋 🔔 ⭐️
# *************************
# 当前余额:$100
# 请输入您的下注金额:1
# 旋转中...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# 很遗憾,您本轮未获胜
# 您想再次旋转吗?(Y/N):y
# 当前余额:$99
# 请输入您的下注金额:5
# 旋转中...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# 很遗憾,您本轮未获胜
# 您想再次旋转吗?(Y/N):y
# 当前余额:$94
# 请输入您的下注金额:90
# 旋转中...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# 很遗憾,您本轮未获胜
# 您想再次旋转吗?(Y/N):y
# 当前余额:$4
# 请输入您的下注金额:1
# 旋转中...
#
# *************
# 🔔 | 🔔 | 🔔
# *************
# 您赢得了 $10
# 您想再次旋转吗?(Y/N):n
# ******************************************
# 游戏结束!您的最终余额为 $14
# ******************************************

43. ⭐ 加密程序 🔐

import string

# chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars = " " + string.punctuation + string.digits + string.ascii_letters

print(chars)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
import string

chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)

print(chars)
# [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
import string

chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()

print(f"字符集: {chars}")
print(f"密钥  : {key}")
# 字符集: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 密钥  : [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
import random
import string

chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()

random.shuffle(key)

print(f"字符集: {chars}")
print(f"密钥  : {key}")
# 字符集: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 密钥  : ['k', '9', 'V', '=', '!', 'K', 'q', 'w', 'O', '}', 'Y', 'S', 'B', '*', 'm', '(', '[', 'G', '>', ' ', 'N', '^', ']', 'u', 'H', '/', 'l', 'z', 'v', 'c', ';', 'p', '_', 'M', '#', 'r', '3', 'J', 'e', 'D', 'I', '&', '2', '1', 'W', 't', 'j', '@', 'h', '6', 'i', '0', 'y', '.', 'Z', 'U', 'P', 'A', 'd', 'n', 'T', '4', 'E', 'x', 'Q', '7', 'f', '-', '"', 'o', 'b', '8', '|', '$', '~', 'C', 'X', 'R', ':', 'g', '?', ')', '+', 'F', '{', 's', '5', ',', 'L', '`', '%', 'a', '<', '\\', "'", 'T']
import random
import string

chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()

random.shuffle(key)

print(f"字符集: {chars}")
print(f"密钥  : {key}")

# 加密
plain_text = input("请输入要加密的消息: ")
cipher_text = ""

for letter in plain_text:
    index = chars.index(letter)
    cipher_text += key[index]

print(f"原始消息: {plain_text}")
print(f"加密消息: {cipher_text}")
# 请输入要加密的消息: I like pizza!
# 字符集: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 密钥  : ['k', '9', 'V', '=', '!', 'K', 'q', 'w', 'O', '}', 'Y', 'S', 'B', '*', 'm', '(', '[', 'G', '>', 'R', ']', 'u', 'H', '/', 'l', 'z', 'c', ';', 'p', '_', 'M', '#', 'T', '4', '1', '2', '3', '0', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'y', 'L', 'x', 'n', 'o', 'p', 'q', 'r', 's', 't', 'A', 'v', 'W', 'X', 'Z', 't', 'J', 'C', 'P', 'Q', 'U', 'E', 'F', 'I', 'D', 'N', 'B', 'y', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 原始消息: I like pizza!
# 加密消息: D Liye piJJa9
import random
import string

chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()

random.shuffle(key)

# print(f"字符集: {chars}")
# print(f"密钥  : {key}")

# 加密
plain_text = input("请输入要加密的消息: ")
cipher_text = ""

for letter in plain_text:
    index = chars.index(letter)
    cipher_text += key[index]

print(f"原始消息: {plain_text}")
print(f"加密消息: {cipher_text}")

# 解密
cipher_text = input("请输入要解密的消息: ")
plain_text = ""

for letter in cipher_text:
    index = key.index(letter)
    plain_text += chars[index]

print(f"加密消息: {cipher_text}")
print(f"原始消息: {plain_text}")
# 请输入要加密的消息: I like pizza!
# 原始消息: I like pizza!
# 加密消息: NkLiyekpiJJa9
# 请输入要解密的消息: NkLiyekpiJJa9
# 加密消息: NkLiyekpiJJa9
# 原始消息: I like pizza!

44. ⭐ 猜字游戏 🕺

# Python 猜字游戏
import random

words = ("apple", "orange", "banana", "coconut", "pineapple")

# 键值对字典,用于存储不同错误次数对应的图形
hangman_art = {0: ("   ",
                   "   ",
                   "   "),
               1: (" o ",
                   "   ",
                   "   ",
                   "   "),
               2: (" o ",
                   " | ",
                   "   "),
               3: (" o ",
                   "/| ",
                   "   "),
               4: (" o ",
                   "/|\\",
                   "   "),
               5: (" o ",
                   "/|\\",
                   "/  "),
               6: (" o ",
                   "/|\\",
                   "/ \\")}

# 示例:打印错误次数为3时的图形
# print(hangman_art[3])
# (' o ', '/| ', '   ')

for line in hangman_art[3]:
    print(line)
#  o 
# /| 
#    
import random

words = ("apple", "orange", "banana", "coconut", "pineapple")

# 键值对字典,用于存储不同错误次数对应的图形
hangman_art = {0: ("   ",
                   "   ",
                   "   "),
               1: (" o ",
                   "   ",
                   "   ",
                   "   "),
               2: (" o ",
                   " | ",
                   "   "),
               3: (" o ",
                   "/| ",
                   "   "),
               4: (" o ",
                   "/|\\",
                   "   "),
               5: (" o ",
                   "/|\\",
                   "/  "),
               6: (" o ",
                   "/|\\",
                   "/ \\")}

def display_man(wrong_guesses):
    print("**********")
    for line in hangman_art[wrong_guesses]:
        print(line)  
    print("**********")  

def display_hint(hint):
    pass

def display_answer(answer):
    pass

def main():
    answer = random.choice(words)
    # print(answer)
    # apple
    hint = ["_"] * len(answer)
    # print(hint)
    # ['_', '_', '_', '_', '_']
    wrong_guesses = 6
    guessed_letters = set()
    is_running = True

    while is_running:
        display_man(wrong_guesses)
        display_hint(hint)
        guess = input("请输入一个字母:").lower()

if __name__ == '__main__':
    main()
# **********
#  o 
# /|\
# / \
# **********
# 请输入一个字母:
# wordslist.py
words = ("apple", "orange", "banana", "coconut", "pineapple")
# main.py
from wordslist import words
import random

# 键值对字典,用于存储不同错误次数对应的图形
hangman_art = {0: ("   ",
                   "   ",
                   "   "),
               1: (" o ",
                   "   ",
                   "   ",
                   "   "),
               2: (" o ",
                   " | ",
                   "   "),
               3: (" o ",
                   "/| ",
                   "   "),
               4: (" o ",
                   "/|\\",
                   "   "),
               5: (" o ",
                   "/|\\",
                   "/  "),
               6: (" o ",
                   "/|\\",
                   "/ \\")}

def display_man(wrong_guesses):
    print("**********")
    for line in hangman_art[wrong_guesses]:
        print(line)  
    print("**********")  

def display_hint(hint):
    print(" ".join(hint))

def display_answer(answer):
    print(" ".join(answer))

def main():
    answer = random.choice(words)
    hint = ["_"] * len(answer)
    wrong_guesses = 0
    guessed_letters = set()
    is_running = True

    while is_running:
        display_man(wrong_guesses)
        display_hint(hint)
        guess = input("请输入一个字母:").lower()

        if len(guess) != 1 or not guess.isalpha():
            print("输入无效")
            continue
        if guess in guessed_letters:
            print(f"{guess} 已经被猜过了")
            continue

        guessed_letters.add(guess)

        if guess in answer:
            for i in range(len(answer)):
                if answer[i] == guess:
                    hint[i] = guess
        else:
            wrong_guesses += 1
        
        if "_" not in hint:
            display_man(wrong_guesses)
            display_answer(answer)
            print("你赢了!")
            is_running = False
        elif wrong_guesses >= len(hangman_art) - 1:
            display_man(wrong_guesses)
            display_answer(answer)
            print("你输了!")
            is_running = False

if __name__ == '__main__':
    main()
# **********
#    
#    
#    
# **********
# _ _ _ _ _ _ _ _ _
# 请输入一个字母:p
# **********
#    
#    
#    
# **********
# p _ _ _ _ p p _ _
# 请输入一个字母:&
# 输入无效
# **********
#    
#    
#    
# **********
# p _ _ _ _ p p _ _
# 请输入一个字母:i
# **********
#    
#    
#    
# **********
# p i _ _ _ p p _ _
# 请输入一个字母:n
# **********
#    
#    
#    
# **********
# p i n _ _ p p _ _
# 请输入一个字母:p
# p 已经被猜过了
# **********
#    
#    
#    
# **********
# p i n _ _ p p _ _
# 请输入一个字母:x
# **********
#  o 
#    
#    
#    
# **********
# p i n _ _ p p _ _
# 请输入一个字母:z
# **********
#  o 
#  | 
#    
# **********
# p i n _ _ p p _ _
# 请输入一个字母:e
# **********
#  o 
#  | 
#    
# **********
# p i n e _ p p _ e
# 请输入一个字母:a
# **********
#  o 
#  | 
#    
# **********
# p i n e a p p _ e
# 请输入一个字母:l
# **********
#  o 
#  | 
#    
# **********
# p i n e a p p l e
# 你赢了!

45. Python 面向对象编程 🚗

object(对象) = 相关属性(变量)和方法(函数)的“捆绑”
示例:手机、杯子、书籍
需要使用“类”来创建多个对象

class(类) = (蓝图)用于设计对象的结构和布局

class Car:
    def __init__(self, model, year, color, for_sale):
        self.model = model
        self.year = year
        self.color = color
        self.for_sale = for_sale

car1 = Car("Mustang", 2024, "red", False)

print(car1)
# <__main__.Car object at 0x000001AE490AE610>
print(car1.model)
# Mustang
print(car1.year)
# 2024
print(car1.color)
# red
print(car1.for_sale)
# False
# car.py
class Car:
    def __init__(self, model, year, color, for_sale):
        self.model = model
        self.year = year
        self.color = color
        self.for_sale = for_sale
# main.py
from car import Car

car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)

print(car1.model)
# Mustang
print(car1.year)
# 2024
print(car1.color)
# red
print(car1.for_sale)
# False
# car.py
class Car:
    def __init__(self, model, year, color, for_sale):
        self.model = model
        self.year = year
        self.color = color
        self.for_sale = for_sale
    
    def drive(self):
        print("你正在驾驶汽车")

    def stop(self):
        print("你停下了汽车")
# main.py
from car import Car

car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)

car1.drive()
# 你正在驾驶汽车
car2.drive()
# 你正在驾驶汽车
car1.stop()
# 你停下了汽车
car2.stop()
# 你停下了汽车
# car.py
class Car:
    def __init__(self, model, year, color, for_sale):
        self.model = model
        self.year = year
        self.color = color
        self.for_sale = for_sale
    
    def drive(self):
        print(f"你正在驾驶 {self.color} {self.model}")

    def stop(self):
        print(f"你停下了 {self.color} {self.model}")
    
    def describe(self):
        print(f"{self.year} {self.color} {self.model}")
# main.py
from car import Car

car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)

car1.drive()
# 你正在驾驶 red Mustang
car1.stop()
# 你停下了 red Mustang
car1.describe()
# 2024 red Mustang

46. 类变量 🎓

类变量 = 在类的所有实例之间共享
在构造函数之外定义
允许你在该类的所有对象之间共享数据

class Car:

    wheels = 4 # 类变量

    def __init__(self, model, year):
        self.model = model # 实例变量
        self.year = year # 实例变量
class Student:

    class_year = 2024 # 类变量

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

student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)

print(student1.name)
print(student1.age)
# Spongebob
# 30
print(student1.class_year)
print(student2.class_year)
print(Student.class_year)
# 2024
# 2024
# 2024
class Student:

    class_year = 2024 # 类变量
    num_students = 0 # 类变量

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Student.num_students += 1

student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
student3 = Student("Squidward", 35)
student4 = Student("Sandy", 35)

print(Student.num_students)
# 4
print(f"我的 {Student.class_year} 届毕业班有 {Student.num_students} 名学生")
print(student1.name)
print(student2.name)
print(student3.name)
print(student4.name)
# 我的 2024 届毕业班有 4 名学生
# Spongebob
# Patrick
# Squidward
# Sandy

47. 继承 👨‍👦‍👦

继承 = 允许一个类从另一个类继承属性和方法
有助于代码的可重用性和扩展性
class Child(Parent)
class Sub(Super)

class Father:
    height = 182
    color = "pink"

class Son(Father):
    pass
class Animal:
    def __init__(self, name):
        self.name = name
        self.is_alive = True

    def eat(self):
        print(f"{self.name} 在吃东西")
    
    def sleep(self):
        print(f"{self.name} 在睡觉")

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class Mouse(Animal):
    pass

dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")

print(dog.name)
print(dog.is_alive)
dog.eat()
dog.sleep()
# Scooby
# True
# Scooby 在吃东西
# Scooby 在睡觉
class Animal:
    def __init__(self, name):
        self.name = name
        self.is_alive = True

    def eat(self):
        print(f"{self.name} 在吃东西")
    
    def sleep(self):
        print(f"{self.name} 在睡觉")

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

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

class Mouse(Animal):
    def speak(self):
        print("吱吱!")

dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")

dog.speak()
# 汪汪!

48. 多重继承 🐟

多重继承 = 从多个父类继承
C(A, B)

多重继承 = 从一个继承自另一个父类的父类继承
C(B) <- B(A) <- A

class Prey:
    pass

class Predator:
    pass

class Rabbit:
    pass

class Hawk:
    pass

class Fish:
    pass
class Prey:
    def flee(self):
        print("这只动物在逃跑")

class Predator:
    def hunt(self):
        print("这只动物在狩猎")

class Rabbit(Prey):
    pass

class Hawk(Predator):
    pass

class Fish(Prey, Predator):
    pass

rabbit = Rabbit()
hawk = Hawk()
fish = Fish()

rabbit.flee()
# 这只动物在逃跑
rabbit.hunt()
# AttributeError: 'Rabbit' 对象没有 'hunt' 属性
hawk.hunt()
# 这只动物在狩猎
hawk.flee()
# AttributeError: 'Hawk' 对象没有 'flee' 属性
fish.flee()
# 这只动物在逃跑
fish.hunt()
# 这只动物在狩猎
class Animal:
    def __init__(self, name):
        self.name = name
    
    def eat(self):
        print(f"{self.name} 在吃东西")
    
    def sleep(self):
        print(f"{self.name} 在睡觉")

class Prey(Animal):
    def flee(self):
        print(f"{self.name} 在逃跑")

class Predator(Animal):
    def hunt(self):
        print(f"{self.name} 在狩猎")

class Rabbit(Prey):
    pass

class Hawk(Predator):
    pass

class Fish(Prey, Predator):
    pass

rabbit = Rabbit("Bugs")
hawk = Hawk("Tony")
fish = Fish("Nemo")

rabbit.eat()
# Bugs 在吃东西
rabbit.sleep()
# Bugs 在睡觉
rabbit.flee()
# Bugs 在逃跑
hawk.flee()
# AttributeError: 'Hawk' 对象没有 'flee' 属性
hawk.eat()
# Tony 在吃东西
hawk.hunt()
# Tony 在狩猎
fish.eat()
fish.sleep()
fish.flee()
fish.hunt()
# Nemo 在吃东西
# Nemo 在睡觉
# Nemo 在逃跑
# Nemo 在狩猎

49. super() 🔴

super() = 在子类中用于调用父类(超类)的方法的函数。
  允许扩展继承方法的功能。

class Super: # 👨🏻
    pass

class Sub(Super): # 👶🏻
    pass

class super
class super(type, object_or_type=None)
  返回一个代理对象,将方法调用委托给指定类型的父类或同级类。这对于访问在子类中被覆盖的继承方法非常有用。
  object_or_type 参数决定方法解析顺序的搜索范围。搜索从 type 之后的类开始。

class Circle:
    def __init__(self, color, is_filled, radius):
        self.color = color
        self.is_filled = is_filled
        self.radius = radius

class Square:
    def __init__(self, color, is_filled, width):
        self.color = color
        self.is_filled = is_filled
        self.width = width

class Triangle:
    def __init__(self, color, is_filled, width, height):
        self.color = color
        self.is_filled = is_filled
        self.width = width
        self.height = height
class Shape:
    def __init__(self, color, is_filled):
        self.color = color
        self.is_filled = is_filled

class Circle(Shape):
    def __init__(self, color, is_filled, radius):
        super().__init__(color, is_filled)
        self.radius = radius

class Square(Shape):
    def __init__(self, color, is_filled, width):
        super().__init__(color, is_filled)
        self.width = width

class Triangle(Shape):
    def __init__(self, color, is_filled, width, height):
        super().__init__(color, is_filled)
        self.width = width
        self.height = height

circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)

print(circle.color)
print(circle.is_filled)
print(f"{circle.radius}cm")
# 红色
# True
# 5cm
print(square.color)
print(square.is_filled)
print(f"{square.width}cm")
# 蓝色
# False
# 6cm
print(triangle.color)
print(triangle.is_filled)
print(f"{triangle.width}cm")
print(f"{triangle.height}cm")
# 黄色
# True
# 7cm
# 8cm
class Shape:
    def __init__(self, color, is_filled):
        self.color = color
        self.is_filled = is_filled

    def describe(self):
        print(f"它是 {self.color} 并且 {'填充' if self.is_filled else '未填充'}")

class Circle(Shape):
    def __init__(self, color, is_filled, radius):
        super().__init__(color, is_filled)
        self.radius = radius

class Square(Shape):
    def __init__(self, color, is_filled, width):
        super().__init__(color, is_filled)
        self.width = width

class Triangle(Shape):
    def __init__(self, color, is_filled, width, height):
        super().__init__(color, is_filled)
        self.width = width
        self.height = height

circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)

circle.describe()
# 它是红色并且填充
square.describe()
# 它是蓝色并且未填充
triangle.describe()
# 它是黄色并且填充
class Shape:
    def __init__(self, color, is_filled):
        self.color = color
        self.is_filled = is_filled

    def describe(self):
        print(f"它是 {self.color} 并且 {'填充' if self.is_filled else '未填充'}")

class Circle(Shape):
    def __init__(self, color, is_filled, radius):
        super().__init__(color, is_filled)
        self.radius = radius
    
    def describe(self):
        super().describe()
        print(f"它是一个圆,面积为 {3.14 * self.radius * self.radius}cm^2")

class Square(Shape):
    def __init__(self, color, is_filled, width):
        super().__init__(color, is_filled)
        self.width = width
    
    def describe(self):
        super().describe()
        print(f"它是一个正方形,面积为 {self.width * self.width}cm^2")

class Triangle(Shape):
    def __init__(self, color, is_filled, width, height):
        super().__init__(color, is_filled)
        self.width = width
        self.height = height

    def describe(self):
        super().describe()
        print(f"它是一个三角形,面积为 {self.width * self.height / 2}cm^2")

circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)

circle.describe()
# 它是红色并且填充
# 它是一个圆,面积为 78.5cm^2
square.describe()
# 它是蓝色并且未填充
# 它是一个正方形,面积为 36cm^2
triangle.describe()
# 它是黄色并且填充
# 它是一个三角形,面积为 28.0cm^2

50. 多态 🎭

多态 (Polymorphism) = 希腊语,意为“具有多种形态或面貌”
    Poly = 多种
    Morphe = 形态

    实现多态的两种方式
    1. 继承 = 一个对象可以被视为与其父类相同的类型
    2. “鸭子类型” = 对象必须具有必要的属性/方法

class Shape:
    pass

class Circle(Shape):
    pass

class Square(Shape):
    pass

class Triangle(Shape):
    pass

circle = Circle()
square = Square()
triangle = Triangle()

shapes = [Circle(), Square(), Triangle()]
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        self.side = side
    
    def area(self):
        return self.side ** 2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def area(self):
        return self.base * self.height * 0.5

shapes = [Circle(4), Square(5), Triangle(6, 7)]

for shape in shapes:
    print(f"{shape.area()}cm²")
# 50.24cm²
# 25cm²
# 21.0cm²

(如何添加上标 ²):
Windows:Alt + 0178   Mac:Control + Command + Space

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        self.side = side
    
    def area(self):
        return self.side ** 2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def area(self):
        return self.base * self.height * 0.5

class Pizza:
    def __init__(self, topping, radius):
        self.topping = topping
        self.radius = radius

shapes = [Circle(4), Square(5), Triangle(6, 7), Pizza("pepperoni", 15)]

for shape in shapes:
    print(f"{shape.area()}cm²")
# AttributeError: 'Pizza' object has no attribute 'area'
# 50.24cm²
# 25cm²
# 21.0cm²
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        self.side = side
    
    def area(self):
        return self.side ** 2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def area(self):
        return self.base * self.height * 0.5

class Pizza(Circle):
    def __init__(self, topping, radius):
        super().__init__(radius)
        self.topping = topping

shapes = [Circle(4), Square(5), Triangle(6, 7), Pizza("pepperoni", 15)]

for shape in shapes:
    print(f"{shape.area()}cm²")
# 50.24cm²
# 25cm²
# 21.0cm²
# 706.5cm²

51. 鸭子类型 🦆

“鸭子类型” = 实现多态的另一种方式,不依赖继承
        对象必须具备必要的最小属性/方法
        “如果它看起来像鸭子,叫起来像鸭子,那它就是鸭子。”

class Animal:
    alive = True

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

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

class Car():
    def horn(self):
        print("嘟!")

animals = [Dog(), Cat(), Car()]

for animal in animals:
    animal.speak()
# AttributeError: 'Car' 对象没有 'speak' 属性
# 汪!
# 喵!
class Animal:
    alive = True

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

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

class Car():
    def speak(self):
        print("嘟!")

animals = [Dog(), Cat(), Car()]

for animal in animals:
    animal.speak()
    print(animal.alive)
# AttributeError: 'Car' 对象没有 'alive' 属性
# 汪!
# True
# 喵!
# True
# 嘟!
class Animal:
    alive = True

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

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

class Car():
    alive = False

    def speak(self):
        print("嘟!")

animals = [Dog(), Cat(), Car()]

for animal in animals:
    animal.speak()
    print(animal.alive)
# 汪!
# True
# 喵!
# True
# 嘟!
# False

52. 静态方法 ⚡

静态方法 = 属于类而不是该类实例(对象)的方法
        通常用于通用工具函数

实例方法 = 最适合对类实例(对象)进行操作

# 实例方法
def get_info(self):
    return f"{self.name} = {self.position}"

静态方法 = 最适合不需要访问类数据的工具函数

@staticmethod
def km_to_miles(kilometers):
    return kilometers * 0.621371
class Employee:

    def __init__(self, name, position):
        self.name = name
        self.position = position
    
    def get_info(self):
        return f"{self.name} = {self.position}"
    
    @staticmethod
    def is_valid_position(position):
        valid_positions = ["经理", "收银员", "厨师", "清洁工"]
        return position in valid_positions

print(Employee.is_valid_position("厨师"))
# True
print(Employee.is_valid_position("火箭科学家"))
# False
class Employee:

    def __init__(self, name, position):
        self.name = name
        self.position = position
    
    def get_info(self):
        return f"{self.name} = {self.position}"
    
    @staticmethod
    def is_valid_position(position):
        valid_positions = ["经理", "收银员", "厨师", "清洁工"]
        return position in valid_positions

employee1 = Employee("尤金", "经理")
employee2 = Employee("鱿鱼哥", "收银员")
employee3 = Employee("海绵宝宝", "厨师")

print(Employee.is_valid_position("火箭科学家"))
# False
print(employee1.get_info())
print(employee2.get_info())
print(employee3.get_info())
# 尤金 = 经理
# 鱿鱼哥 = 收银员
# 海绵宝宝 = 厨师

53. 类方法 🏫

类方法:允许对类本身进行操作
      以 cls 作为第一个参数,表示类本身。

实例方法:最适合对类实例(对象)的操作
静态方法:最适合无需访问类数据的工具函数
类方法:最适合类级别的数据或需要访问类本身的操作

class Student:

    count = 0

    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa
        Student.count += 1

    # 实例方法
    def get_info(self):
        return f"{self.name} {self.gpa}"

    @classmethod
    def get_count(cls):
        return f"学生总数:{cls.count}"

print(Student.get_count())
# 学生总数:0
class Student:

    count = 0

    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa
        Student.count += 1

    # 实例方法
    def get_info(self):
        return f"{self.name} {self.gpa}"

    @classmethod
    def get_count(cls):
        return f"学生总数:{cls.count}"

student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
student3 = Student("Sandy", 4.0)

print(Student.get_count())
# 学生总数:3
class Student:

    count = 0
    total_gpa = 0

    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa
        Student.count += 1
        Student.total_gpa += gpa  # 修正:累加 gpa

    # 实例方法
    def get_info(self):
        return f"{self.name} {self.gpa}"

    @classmethod
    def get_count(cls):
        return f"学生总数:{cls.count}"

    @classmethod
    def get_average_gpa(cls):
        if cls.count == 0:
            return 0
        else:
            return f"平均 GPA: {cls.total_gpa / cls.count:.2f}"

student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
student3 = Student("Sandy", 4.0)

print(Student.get_count())
# 学生总数:3
print(Student.get_average_gpa())
# 平均 GPA: 3.07

54. 魔法方法 🌟

魔法方法 = 双下划线方法(Dunder methods),如 __init____str____eq__
        它们会被 Python 的许多内置操作自动调用。
        魔法方法允许开发者定义或自定义对象的行为。

class Student:

    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa

    def __str__(self):
        return f"姓名: {self.name} 平均绩点: {self.gpa}"
    
    def __eq__(self, other):
        return self.name == other.name
    
    def __gt__(self, other):
        return self.gpa > other.gpa

student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)

print(student1)
print(student1 == student2)
print(student1 > student2)
# 姓名: Spongebob 平均绩点: 3.2
# False
# True
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)

print(book1)
# <__main__.Book object at 0x000001E78F76EE50>
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)
book4 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)

print(book1)
# 《霍比特人》 作者: J.R.R. Tolkien
print(book3 == book4)
# False
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)
book4 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 17222)

print(book1)
# 《霍比特人》 作者: J.R.R. Tolkien
print(book3 == book4)
# True
print(book2 < book3)
# TypeError: '<' not supported between instances of 'Book' and 'Book'
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
    
    def __lt__(self, other):
        return self.num_pages < other.num_pages
    
    def __gt__(self, other):
        return self.num_pages > other.num_pages

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)
book4 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 17222)

print(book2 < book3)
# False
print(book2 > book3)
# True
print(book2 + book3)
# TypeError: unsupported operand type(s) for +: 'Book' and 'Book'
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
    
    def __lt__(self, other):
        return self.num_pages < other.num_pages
    
    def __gt__(self, other):
        return self.num_pages > other.num_pages

    def __add__(self, other):
        return f"{self.num_pages + other.num_pages} 页"

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)
book4 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 17222)

print(book2 + book3)
# 395 页
print("狮子" in book3)
# TypeError: argument of type 'Book' is not iterable
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
    
    def __lt__(self, other):
        return self.num_pages < other.num_pages
    
    def __gt__(self, other):
        return self.num_pages > other.num_pages

    def __add__(self, other):
        return f"{self.num_pages + other.num_pages} 页"
    
    def __contains__(self, keyword):
        return keyword in self.title or keyword in self.author

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)

print("狮子" in book3)
# True
print("狮子" in book1)
# False
print("Rowling" in book2)
# True
print("Rowling" in book3)
# False
print(book1['title'])
# TypeError: 'Book' object is not subscriptable
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
    
    def __lt__(self, other):
        return self.num_pages < other.num_pages
    
    def __gt__(self, other):
        return self.num_pages > other.num_pages

    def __add__(self, other):
        return f"{self.num_pages + other.num_pages} 页"
    
    def __contains__(self, keyword):
        return keyword in self.title or keyword in self.author

    def __getitem__(self, key):
        if key == "title":
            return self.title

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)

print(book1['title'])
# 霍比特人
print(book2['title'])
# 哈利·波特与魔法石
print(book3['title'])
# 狮子、女巫与魔衣橱
print(book3['author'])
# None
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
    
    def __lt__(self, other):
        return self.num_pages < other.num_pages
    
    def __gt__(self, other):
        return self.num_pages > other.num_pages

    def __add__(self, other):
        return f"{self.num_pages + other.num_pages} 页"
    
    def __contains__(self, keyword):
        return keyword in self.title or keyword in self.author

    def __getitem__(self, key):
        if key == "title":
            return self.title
        elif key == "author":
            return self.author

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)

print(book3['author'])
# C.S. Lewis
print(book2['author'])
# J.K. Rowling
print(book1['author'])
# J.R.R. Tolkien
print(book1['num_pages'])
# None
class Book:

    def __init__(self, title, author, num_pages):
        self.title = title
        self.author = author
        self.num_pages = num_pages

    def __str__(self):
        return f"《{self.title}》 作者: {self.author}"
    
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author
    
    def __lt__(self, other):
        return self.num_pages < other.num_pages
    
    def __gt__(self, other):
        return self.num_pages > other.num_pages

    def __add__(self, other):
        return f"{self.num_pages + other.num_pages} 页"
    
    def __contains__(self, keyword):
        return keyword in self.title or keyword in self.author

    def __getitem__(self, key):
        if key == "title":
            return self.title
        elif key == "author":
            return self.author
        elif key == "num_pages":
            return self.num_pages
        else:
            return f"键 '{key}' 未找到"

book1 = Book("霍比特人", "J.R.R. Tolkien", 310)
book2 = Book("哈利·波特与魔法石", "J.K. Rowling", 223)
book3 = Book("狮子、女巫与魔衣橱", "C.S. Lewis", 172)

print(book1['num_pages'])
# 310
print(book2['num_pages'])
# 223
print(book3['num_pages'])
# 172
print(book3['audio'])
# 键 'audio' 未找到

55. @property ⚙️

@property 是一个装饰器,用于将方法定义为属性(可以像访问属性一样访问方法)。
      优势:在读取、写入或删除属性时可以添加额外的逻辑。
      提供 getter、setter 和 deleter 方法。

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

rectangle = Rectangle(3, 4)

print(rectangle.width)
print(rectangle.height)
# 3
# 4
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height
    
    @property
    def width(self):
        pass
    
    @property
    def height(self):
        pass

rectangle = Rectangle(3, 4)

print(rectangle.width)
print(rectangle.height)
# 3
# 4
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height
    
    @property
    def width(self):
        return f"{self._width:.1f}cm"
    
    @property
    def height(self):
        return f"{self._height:.1f}cm"

rectangle = Rectangle(3, 4)

print(rectangle.width)
print(rectangle.height)
# 3.0cm
# 4.0cm
print(rectangle._width)
print(rectangle._height)
# 3
# 4
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height
    
    @property
    def width(self):
        return f"{self._width:.1f}cm"
    
    @property
    def height(self):
        return f"{self._height:.1f}cm"

    @width.setter
    def width(self, new_width):
        if new_width > 0:
            self._width = new_width
        else:
            print("宽度必须大于零")

    @height.setter
    def height(self, new_height):
        if new_height > 0:
            self._height = new_height
        else:
            print("高度必须大于零")
    

rectangle = Rectangle(3, 4)

rectangle.width = 0
rectangle.height = -1

print(rectangle.width)
print(rectangle.height)
# 宽度必须大于零
# 高度必须大于零
# 3.0cm
# 4.0cm
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height
    
    @property
    def width(self):
        return f"{self._width:.1f}cm"
    
    @property
    def height(self):
        return f"{self._height:.1f}cm"

    @width.setter
    def width(self, new_width):
        if new_width > 0:
            self._width = new_width
        else:
            print("宽度必须大于零")

    @height.setter
    def height(self, new_height):
        if new_height > 0:
            self._height = new_height
        else:
            print("高度必须大于零")
    

rectangle = Rectangle(3, 4)

rectangle.width = 5
rectangle.height = 6

print(rectangle.width)
print(rectangle.height)
# 5.0cm
# 6.0cm
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height
    
    @property
    def width(self):
        return f"{self._width:.1f}cm"
    
    @property
    def height(self):
        return f"{self._height:.1f}cm"

    @width.setter
    def width(self, new_width):
        if new_width > 0:
            self._width = new_width
        else:
            print("宽度必须大于零")

    @height.setter
    def height(self, new_height):
        if new_height > 0:
            self._height = new_height
        else:
            print("高度必须大于零")
    
    @width.deleter
    def width(self):
        del self._width
        print("宽度已被删除")
    
    @height.deleter
    def height(self):
        del self._height
        print("高度已被删除")
    

rectangle = Rectangle(3, 4)

rectangle.width = 5
rectangle.height = 6

del rectangle.width
del rectangle.height
# 宽度已被删除
# 高度已被删除

56. 装饰器 🎊

装饰器 = 一个扩展另一个函数行为的函数
      无需修改原函数
      将原函数作为参数传递给装饰器

      @add_sprinkles
      get_ice_cream(“vanilla”)

def get_ice_cream():
    print("这是你的冰淇淋 🍨")

get_ice_cream()
# 这是你的冰淇淋 🍨
def add_sprinkles(func):
    def wrapper():
        func() # print("这是你的冰淇淋 🍨")
    return wrapper

@add_sprinkles
def get_ice_cream():
    print("这是你的冰淇淋 🍨")

get_ice_cream()
# 这是你的冰淇淋 🍨
def add_sprinkles(func):
    def wrapper():
        print("*你添加了彩糖 🎊*")
        func()
    return wrapper

@add_sprinkles
def get_ice_cream():
    print("这是你的冰淇淋 🍨")

get_ice_cream()
# *你添加了彩糖 🎊*
# 这是你的冰淇淋 🍨
def add_sprinkles(func):
    print("*你添加了彩糖 🎊*")
    func()

@add_sprinkles
def get_ice_cream():
    print("这是你的冰淇淋 🍨")

# *你添加了彩糖 🎊*
# 这是你的冰淇淋 🍨
def add_sprinkles(func):
    def wrapper():
        print("*你添加了彩糖 🎊*")
        func()
    return wrapper

def add_fudge(func):
    def wrapper():
        print("*你添加了巧克力酱 🍫*")
        func()
    return wrapper

@add_sprinkles
@add_fudge
def get_ice_cream():
    print("这是你的冰淇淋 🍨")

get_ice_cream()
# *你添加了彩糖 🎊*
# *你添加了巧克力酱 🍫*
# 这是你的冰淇淋 🍨
def add_sprinkles(func):
    def wrapper():
        print("*你添加了彩糖 🎊*")
        func()
    return wrapper

def add_fudge(func):
    def wrapper():
        print("*你添加了巧克力酱 🍫*")
        func()
    return wrapper

@add_sprinkles
@add_fudge
def get_ice_cream(flavo):
    print(f"这是你的{flavo}冰淇淋 🍨")

get_ice_cream("vanilla")
# TypeError: add_sprinkles.<locals>.wrapper() 接受 0 个位置参数,但给定了 1 个
def add_sprinkles(func):
    def wrapper(*args, **kwargs):
        print("*你添加了彩糖 🎊*")
        func(*args, **kwargs)
    return wrapper

def add_fudge(func):
    def wrapper(*args, **kwargs):
        print("*你添加了巧克力酱 🍫*")
        func(*args, **kwargs)
    return wrapper

@add_sprinkles
@add_fudge
def get_ice_cream(flavo):
    print(f"这是你的{flavo}冰淇淋 🍨")

get_ice_cream("vanilla")
# *你添加了彩糖 🎊*
# *你添加了巧克力酱 🍫*
# 这是你的vanilla冰淇淋 🍨

57. 异常处理 🚦

异常 = 中断程序流程的事件
      (ZeroDivisionError、TypeError、ValueError)
      1. try, 2. except, 3. finally

1 / 0
# ZeroDivisionError: 除以零
1 + "1"
# TypeError: 对于 + 操作,'int' 和 'str' 类型不受支持
int("pizza")
# ValueError: 以 10 为基数的 int() 无效字面量:'pizza'
try:
    # 尝试运行一些代码
except Exception:
    # 处理异常
finally:
    # 进行一些清理工作
number = int(input("请输入一个数字:"))
print(1 / number)
# 输入一个数字:0
# ZeroDivisionError: 除以零
# 输入一个数字:pizza
# ValueError: 以 10 为基数的 int() 无效字面量:'pizza'
try:
    number = int(input("请输入一个数字:"))
    print(1 / number)
except ZeroDivisionError:
    print("你不能除以零,傻瓜!")
except ValueError:
    print("请输入数字!")
# 输入一个数字:0
# 你不能除以零,傻瓜!
# 输入一个数字:pizza
# 请输入数字!
try:
    number = int(input("请输入一个数字:"))
    print(1 / number)
except ZeroDivisionError:
    print("你不能除以零,傻瓜!")
except ValueError:
    print("请输入数字!")
except Exception: # 过于宽泛的异常条款
    print("出错了!")
finally:
    print("在这里进行一些清理工作")
# 输入一个数字:0
# 你不能除以零,傻瓜!
# 在这里进行一些清理工作
# 输入一个数字:1
# 1.0
# 在这里进行一些清理工作

异常类型有很多种,你可以随时查看 Python 官方文档 获取详细列表。这就是 Python 中的异常处理。

58. 文件检测 🕵️‍♂️

<!-- test.txt -->
喜欢披萨
# main.py
import os

file_path = "test.txt"

if os.path.exists(file_path):
    print(f"位置 '{file_path}' 存在")
else:
    print("该位置不存在")
# 输出:位置 'test.txt' 存在
# main.py
import os

file_path = "test.txt"

if os.path.exists(file_path):
    print(f"位置 '{file_path}' 存在")

    if os.path.isfile(file_path):
        print("这是一个文件")
    elif os.path.isdir(file_path):
        print("这是一个目录")
else:
    print("该位置不存在")
# 输出:
# 位置 'test.txt' 存在
# 这是一个文件

59. 写入文件 ✍

Python 写入文件(.txt、.json、.csv)

txt_data = "我喜欢披萨!"

file_path = "output.txt"

with open(file_path, "w") as file:
    file.write(txt_data)
    print(f"文本文件 '{file_path}' 已创建")

# 文本文件 'output.txt' 已创建
# <!-- output.txt -->
# 我喜欢披萨!
txt_data = "我喜欢披萨!"

file_path = "output.txt"

try:
    with open(file_path, "x") as file:
        file.write(txt_data)
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")
# 该文件已存在!

<!-- output.txt -->
我喜欢披萨!
txt_data = "我喜欢披萨!"

file_path = "output.txt"

try:
    with open(file_path, "a") as file:
        file.write(txt_data)
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")
# 文本文件 'output.txt' 已创建
# <!-- output.txt -->
# 我喜欢披萨!我喜欢披萨!

<!-- output.txt -->
我喜欢披萨!我喜欢披萨!
txt_data = "我喜欢披萨!"

file_path = "output.txt"

try:
    with open(file_path, "a") as file:
        file.write(txt_data)
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")
# 文本文件 'output.txt' 已创建
# <!-- output.txt -->
# 我喜欢披萨!

<!-- output.txt -->
我喜欢披萨!
txt_data = "我喜欢披萨!"

file_path = "output.txt"

try:
    with open(file_path, "a") as file:
        file.write("\n" + txt_data)
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")
# 文本文件 'output.txt' 已创建
# <!-- output.txt -->
# 我喜欢披萨!
# 我喜欢披萨!

employees = ["尤金", "鱿鱼哥", "海绵宝宝", "派大星"]

file_path = "output.txt"

try:
    with open(file_path, "w") as file:
        file.write(employees)
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")

# TypeError: write() 参数必须是字符串,而不是列表
employees = ["尤金", "鱿鱼哥", "海绵宝宝", "派大星"]

file_path = "output.txt"

try:
    with open(file_path, "w") as file:
        for employee in employees:
            file.write(employee)
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")

# 文本文件 'output.txt' 已创建
# <!-- output.txt -->
# 尤金鱿鱼哥海绵宝宝派大星
employees = ["尤金", "鱿鱼哥", "海绵宝宝", "派大星"]

file_path = "output.txt"

try:
    with open(file_path, "w") as file:
        for employee in employees:
            file.write(employee + "\n")
        print(f"文本文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")

# 文本文件 'output.txt' 已创建
# <!-- output.txt -->
# 尤金
# 鱿鱼哥
# 海绵宝宝
# 派大星
import json

employee = {
    "name": "海绵宝宝",
    "age": 30,
    "job": "厨师"
}

file_path = "output.json"

try:
    with open(file_path, "w") as file:
        json.dump(employee, file)
        print(f"JSON 文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")

# JSON 文件 'output.json' 已创建
# <!-- output.json -->
# {"name": "海绵宝宝", "age": 30, "job": "厨师"}
import json

employee = {
    "name": "海绵宝宝",
    "age": 30,
    "job": "厨师"
}

file_path = "output.json"

try:
    with open(file_path, "w") as file:
        json.dump(employee, file, indent=4)
        print(f"JSON 文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")

# JSON 文件 'output.json' 已创建
# <!-- output.json -->
# {
#     "name": "海绵宝宝",
#     "age": 30,
#     "job": "厨师"
# }
import json
import csv

employees = [["姓名", "年龄", "职业"],
             ["海绵宝宝", 30, "厨师"],
             ["派大星", 37, "无业"],
             ["珊迪", 27, "科学家"]]

file_path = "output.csv"

try:
    with open(file_path, "手法
    with open(file_path, "w") as file:
        writer = csv.writer(file)
        for row in employees:
            writer.writerow(row)
        print(f"CSV 文件 '{file_path}' 已创建")
except FileExistsError:
        print("该文件已存在!")

# CSV 文件 'output.csv' 已创建
# <!-- output.csv -->
# 姓名,年龄,职业
# 
# 海绵宝宝,30,厨师
# 
# 派大星,37,无业
# 
# 珊迪,27,科学家
import json
import csv

employees = [["姓名", "年龄", "职业"],
             ["海绵宝宝", 30, "厨师"],
             ["派大星", 37, "无业"],
             ["珊迪", 27, "科学家"]]

file_path = "output.csv"

try:
    with open(file_path, "w", newline="") as file:
        writer = csv.writer(file)
        for row in employees:
            writer.writerow(row)
        print(f"CSV 文件 '{file_path}' 已创建")
except FileExistsError:
    print("该文件已存在!")

# CSV 文件 'output.csv' 已创建
# <!-- output.csv -->
# 姓名,年龄,职业
# 海绵宝宝,30,厨师
# 派大星,37,无业
# 珊迪,27,科学家

60. 读取文件 🔍

Python 读取文件(.txt、.json、csv)

<!-- input.txt -->
我喜欢披萨!
它真的很好吃!
// input.json
{
    "name": "海绵宝宝",
    "age": 30,
    "job": "厨师"
}
<!-- input.csv -->
姓名,年龄,职业
海绵宝宝,30,厨师
派大星,37,无业
珊迪,27,科学家
file_path = "input.txt"

with open(file_path, "r") as file:
    content = file.read()
    print(content)
# 我喜欢披萨!
# 它真的很好吃!

with 语句用于封装一个代码块的执行,通过上下文管理器定义的方法(参见 With 语句上下文管理器 部分)。这可以将常见的 try...except...finally 使用模式封装起来,便于重用。

import json

file_path = "input.json"

try:
    with open(file_path, "r") as file:
        content = json.load(file)
        print(content)
        print(content["name"])
except FileNotFoundError:
    print("未找到该文件")
except PermissionError:
    print("您没有权限读取该文件")

# {"name": "海绵宝宝", "age": 30, "job": "厨师"}
# 海绵宝宝
import csv

file_path = "input.csv"

try:
    with open(file_path, "r") as file:
        content = csv.reader(file)
        print(content)
except FileNotFoundError:
    print("未找到该文件")
except PermissionError:
    print("您没有权限读取该文件")

# <_csv.reader object at 0x0000017D81C4EAA0>
import csv

file_path = "input.csv"

try:
    with open(file_path, "r") as file:
        content = csv.reader(file)
        for line in content:
            print(line)
except FileNotFoundError:
    print("未找到该文件")
except PermissionError:
    print("您没有权限读取该文件")

# ['姓名', '年龄', '职业']
# ['海绵宝宝', '30', '厨师']
# ['派大星', '37', '无业']
# ['珊迪', '27', '科学家']
import csv

file_path = "input.csv"

try:
    with open(file_path, "r") as file:
        content = csv.reader(file)
        for line in content:
            print(line[0])
except FileNotFoundError:
    print("未找到该文件")
except PermissionError:
    print("您没有权限读取该文件")

# 姓名
# 海绵宝宝
# 派大星
# 珊迪

61. 日期与时间 📅

import datetime

date = datetime.date(2025, 1, 2)
print(date)
# 2025-01-02

today = datetime.date.today()
print(today)
# 2025-05-02

time = datetime.time(12, 30, 0)
print(time)
# 12:30:00

now = datetime.datetime.now()
print(now)
# 2025-05-02 09:41:55.409676

now = now.strftime("%H %M %S")
print(now)
# 09 41 55

now = now.strftime("%H:%M:%S")
print(now)
# 09:41:55

now = now.strftime("%H:%M:%S %m-%d-%Y")
print(now)
# 09:41:55 05-02-2025
指令 含义 示例 备注
%a 工作日,基于本地语言的缩写名称。 Sun, Mon, …, Sat (en_US);
So, Mo, …, Sa (de_DE)
(1)
%A 工作日,基于本地语言的完整名称。 Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
(1)
%w 工作日,十进制数字表示,0为周日,6为周六。 0, 1, …, 6
%d 月份中的日期,零填充的十进制数字。 01, 02, …, 31 (9)
%b 月份,基于本地语言的缩写名称。 Jan, Feb, …, Dec (en_US);
Jan, Feb, …, Dez (de_DE)
(1)
%B 月份,基于本地语言的完整名称。 January, February, …, December (en_US);
Januar, Februar, …, Dezember (de_DE)
(1)
%m 月份,零填充的十进制数字。 01, 02, …, 12 (9)
%y 不带世纪的年份,零填充的十进制数字。 00, 01, …, 99 (9)
%Y 带世纪的年份,十进制数字。 0001, 0002, …, 2013, 2014, …, 9998, 9999 (2)

strftime 支持多种格式代码。你可以随时查阅 Python strftime 文档 获取完整的格式代码列表和详细说明。

import datetime

date = datetime.date(2025, 1, 2)
today = datetime.date.today()

time = datetime.time(12, 30, 0)
now = datetime.datetime.now()

now = now.strftime("%H:%M:%S %m-%d-%Y")

target_datetime = datetime.datetime(2030, 1, 2, 12, 12, 30, 1)
curren_datetime = datetime.datetime.now()

if target_datetime < curren_datetime:
    print("目标日期已过去")
else:
    print("目标日期尚未过去")
# 目标日期尚未过去

62. ⭐ 闹钟 ⏰

# Python 闹钟
import time
import datetime
import pygame # pip install pygame

def set_alarm(alarm_time): # 例如 "23:00:00"
    pass

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)
# Python 闹钟
import time
import datetime
import pygame

def set_alarm(alarm_time):
    print(f"闹钟已设置为 {alarm_time}")
    sound_file = "my_music.mp3"

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)

# pygame 2.6.0 (SDL 2.28.4, Python 3.12.5)
# 来自 pygame 社区的问候。https://www.pygame.org/contribute.html
👆"此功能实现在 pygame 库的初始化文件中 (/.venv/Lib/site-packages/pygame/__init__.py 第338-342行)。"
# 请输入闹钟时间 (HH:MM:SS): 09:00:00
# 闹钟已设置为 09:00:00
# Python 闹钟
import time
import datetime
import pygame

def set_alarm(alarm_time):
    print(f"闹钟已设置为 {alarm_time}")
    sound_file = "my_music.mp3"
    is_running = True

    while is_running:
        curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
        print(curren_datetime)

        is_running = False

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)

# 请输入闹钟时间 (HH:MM:SS): 10:00:00
# 闹钟已设置为 10:00:00
# 09:42:16
# Python 闹钟
import time
import datetime
import pygame

def set_alarm(alarm_time):
    print(f"闹钟已设置为 {alarm_time}")
    sound_file = "my_music.mp3"
    is_running = True

    while is_running:
        curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
        print(curren_datetime)

        time.sleep(1)

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)

# 请输入闹钟时间 (HH:MM:SS): 10:00:00
# 闹钟已设置为 10:00:00
# 09:42:16
# 09:42:17
# 09:42:18
# ...
# Python 闹钟
import time
import datetime
import pygame

def set_alarm(alarm_time):
    print(f"闹钟已设置为 {alarm_time}")
    sound_file = "my_music.mp3"
    is_running = True

    while is_running:
        curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
        print(curren_datetime)

        if curren_datetime == alarm_time:
            print("起床啦!🫩")

            is_running = False

        time.sleep(1)

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)

# 请输入闹钟时间 (HH:MM:SS): 09:45:00
# 闹钟已设置为 09:45:00
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# 起床啦!🫩

# 进程以退出码 0 结束
# Python 闹钟
import time
import datetime
import pygame

def set_alarm(alarm_time):
    print(f"闹钟已设置为 {alarm_time}")
    sound_file = "my_music.mp3"
    is_running = True

    while is_running:
        curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
        print(curren_datetime)

        if curren_datetime == alarm_time:
            print("起床啦!🫩")

            pygame.mixer.init()
            pygame.mixer.music.load(sound_file)
            pygame.mixer.music.play()

            is_running = False

        time.sleep(1)

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)

# 请输入闹钟时间 (HH:MM:SS): 09:45:00
# 闹钟已设置为 09:45:00
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# 起床啦!🫩

# 进程以退出码 0 结束

模块 pygame.mixer: 用于加载和播放声音的 pygame 模块

# pygame.mixer
def init(frequency: int = 44100,
         size: int = -16,
         channels: int = 2,
         buffer: int = 512,
         devicename: str | None = None,
         allowedchanges: int = 5) -> None

# Python 闹钟
import time
import datetime
import pygame

def set_alarm(alarm_time):
    print(f"闹钟已设置为 {alarm_time}")
    sound_file = "my_music.mp3"
    is_running = True

    while is_running:
        curren_datetime = datetime.datetime.now().strftime("%H:%M:%S")
        print(curren_datetime)

        if curren_datetime == alarm_time:
            print("起床啦!🫩")

            pygame.mixer.init()
            pygame.mixer.music.load(sound_file)
            pygame.mixer.music.play()

            while pygame.mixer.music.get_busy():
                time.sleep(1)

            is_running = False

        time.sleep(1)

if __name__ == '__main__':
    alarm_time = input("请输入闹钟时间 (HH:MM:SS): ")
    set_alarm(alarm_time)

# 请输入闹钟时间 (HH:MM:SS): 09:45:00
# 闹钟已设置为 09:45:00
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# 起床啦!🫩

👆这就是如何用 Python 创建一个闹钟。

63. 多线程 🧵

多线程 = 用于同时执行多个任务(multithreading)
      适用于I/O密集型任务,如读取文件或从API获取数据
      threading.Thread(target=my_function)

import threading
import time

def walk_dog():
    time.sleep(8)
    print("你遛完狗了")

def take_out_trash():
    time.sleep(2)
    print("你倒完垃圾了")

def get_mail():
    time.sleep(4)
    print("你取完邮件了")

walk_dog()
take_out_trash()
get_mail()

# 你遛完狗了
# 你倒完垃圾了
# 你取完邮件了
import threading
import time

def walk_dog():
    time.sleep(8)
    print("你遛完狗了")

def take_out_trash():
    time.sleep(2)
    print("你倒完垃圾了")

def get_mail():
    time.sleep(4)
    print("你取完邮件了")

chore1 = threading.Thread(target=walk_dog)
chore1.start()

chore2 = threading.Thread(target=take_out_trash)
chore2.start()

chore3 = threading.Thread(target=get_mail)
chore3.start()

print("所有家务都完成了!")

# 所有家务都完成了!
# 你倒完垃圾了
# 你取完邮件了
# 你遛完狗了
import threading
import time

def walk_dog():
    time.sleep(8)
    print("你遛完狗了")

def take_out_trash():
    time.sleep(2)
    print("你倒完垃圾了")

def get_mail():
    time.sleep(4)
    print("你取完邮件了")

chore1 = threading.Thread(target=walk_dog)
chore1.start()

chore2 = threading.Thread(target=take_out_trash)
chore2.start()

chore3 = threading.Thread(target=get_mail)
chore3.start()

print("所有家务都完成了!")

chore1.join()
chore2.join()
chore3.join()

# 你倒完垃圾了
# 你取完邮件了
# 你遛完狗了
# 所有家务都完成了!
import threading
import time

def walk_dog(first):
    time.sleep(8)
    print(f"你遛完{first}了")

def take_out_trash():
    time.sleep(2)
    print("你倒完垃圾了")

def get_mail():
    time.sleep(4)
    print("你取完邮件了")

# 被解释为括号中的字符串
chore1 = threading.Thread(target=walk_dog, args=("Scooby",))
chore1.start()

chore2 = threading.Thread(target=take_out_trash)
chore2.start()

chore3 = threading.Thread(target=get_mail)
chore3.start()

print("所有家务都完成了!")

chore1.join()
chore2.join()
chore3.join()

# 你倒完垃圾了
# 你取完邮件了
# 你遛完Scooby了
# 所有家务都完成了!
import threading
import time

def walk_dog(first):
    time.sleep(8)
    print(f"你遛完{first}了")

def take_out_trash():
    time.sleep(2)
    print("你倒完垃圾了")

def get_mail():
    time.sleep(4)
    print("你取完邮件了")

# 被解释为括号中的字符串
chore1 = threading.Thread(target=walk_dog, args=("Scooby"))
chore1.start()

chore2 = threading.Thread(target=take_out_trash)
chore2.start()

chore3 = threading.Thread(target=get_mail)
chore3.start()

print("所有家务都完成了!")

chore1.join()
chore2.join()
chore3.join()

# TypeError: walk_dog() 接受1个位置参数,但给出了6个
# 你倒完垃圾了
# 你取完邮件了
# 你遛完Scooby了
# 所有家务都完成了!
import threading
import time

def walk_dog(first, last):
    time.sleep(8)
    print(f"你遛完{first} {last}了")

def take_out_trash():
    time.sleep(2)
    print("你倒完垃圾了")

def get_mail():
    time.sleep(4)
    print("你取完邮件了")

# 被解释为括号中的字符串
chore1 = threading.Thread(target=walk_dog, args=("Scooby", "Doo"))
chore1.start()

chore2 = threading.Thread(target=take_out_trash)
chore2.start()

chore3 = threading.Thread(target=get_mail)
chore3.start()

print("所有家务都完成了!")

chore1.join()
chore2.join()
chore3.join()

# 你倒完垃圾了
# 你取完邮件了
# 你遛完Scooby Doo了
# 所有家务都完成了!

64. 请求 API 数据 ↩️

PokéAPI
示例:https://pokeapi.co/api/v2/pokemon/pikachu

# 如何使用 Python 连接到 API
import requests # 需要安装 requests:pip install requests

base_url = "https://pokeapi.co/api/v2/"

def get_pokemon_info(name):
    pass

pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
import requests

base_url = "https://pokeapi.co/api/v2/"

def get_pokemon_info(name):
    url = f"{base_url}/pokemon/{name}"
    response = requests.get(url)
    print(response)

pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)

# <Response [200]>

HTTP 响应状态码

import requests

base_url = "https://pokeapi.co/api/v2/"

def get_pokemon_info(name):
    url = f"{base_url}/pokemon/{name}"
    response = requests.get(url)

    if response.status_code == 200:
        print("数据获取成功!")
    else:
        print(f"数据获取失败,状态码:{response.status_code}")

pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)

# 数据获取成功!
import requests

base_url = "https://pokeapi.co/api/v2/"

def get_pokemon_info(name):
    url = f"{base_url}/pokemon/{name}"
    response = requests.get(url)

    if response.status_code == 200:
        pokemon_data = response.json()
        print(pokemon_data)
    else:
        print(f"数据获取失败,状态码:{response.status_code}")

pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)

# {
#   "abilities": [
#     {
#       "ability": {
#         "name": "static",
#         "url": "https://pokeapi.co/api/v2/ability/9/"
#       },
#       "is_hidden": false,
#       "slot": 1
#     },
#     {
#       "ability": {
#         "name": "lightning-rod",
#         "url": "https://pokeapi.co/api/v2/ability/31/"
#       },
#       "is_hidden": true,
#       "slot": 3
#     }
#   ],
#   "base_experience": 112,
#   "height": 4,
#   "id": 25,
#   "name": "pikachu",
#   "types": [
#     {
#       "slot": 1,
#       "type": {
#         "name": "electric",
#         "url": "https://pokeapi.co/api/v2/type/13/"
#       }
#     }
#   ],
#   "weight": 60
# }
import requests

base_url = "https://pokeapi.co/api/v2/"

def get_pokemon_info(name):
    url = f"{base_url}/pokemon/{name}"
    response = requests.get(url)

    if response.status_code == 200:
        pokemon_data = response.json()
        return pokemon_data
    else:
        print(f"数据获取失败,状态码:{response.status_code}")

pokemon_name = "pikachu"
pokemon_info = get_pokemon_info(pokemon_name)

if pokemon_info:
    print(f"名称: {pokemon_info['name'].capitalize()}")
    print(f"ID: {pokemon_info['id']}")
    print(f"身高: {pokemon_info['height']}")
    print(f"体重: {pokemon_info['weight']}")
# 名称: Pikachu
# ID: 25
# 身高: 4
# 体重: 60

65. PyQt5 GUI 简介 🖥️

图形用户界面

# PyQt5 简介
import sys
# pip install PyQt5
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
    
def main():
    pass

if __name__ == '__main__':
    main()

sys — 系统特定的参数和函数
该模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数。它始终可用。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
    
def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

if __name__ == '__main__':
    main()

# 
# 进程以退出代码 0 结束

sys.argv
传递给 Python 脚本的命令行参数列表。argv[0] 是脚本名称(是否为完整路径名取决于操作系统)。如果使用解释器的 -c 命令行选项执行命令,argv[0] 被设置为字符串 '-c'。如果没有向 Python 解释器传递脚本名称,argv[0] 为空字符串。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QIcon

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("我的第一个酷炫 GUI")
        self.setGeometry(700, 300, 500, 500)
        # self.setGeometry(x, y, 宽度, 高度)
        self.setWindowIcon(QIcon("profile_pic.jpg"))
    
def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

66. PyQt5 标签 🏷️

# PyQt5 QLabel 示例
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

        label = QLabel("你好", self) # (窗口将作为父控件)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QFont

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

        label = QLabel("你好", self)
        label.setFont(QFont("Arial", 40))
        label.setGeometry(0, 0, 500, 100)
        label.setStyleSheet("color: #1fff5a;"
                            "background-color: #6fdcf7;"
                            "font-weight: bold;"
                            "font-style: italic;"
                            "text-decoration: underline;") # 可通过谷歌搜索“颜色选择器”获取颜色代码

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

        label = QLabel("你好", self)
        label.setFont(QFont("Arial", 40))
        label.setGeometry(0, 0, 500, 100)
        label.setStyleSheet("color: #1fff5a;"
                            "background-color: #6fdcf7;"
                            "font-weight: bold;"
                            "font-style: italic;"
                            "text-decoration: underline;")
        
        # label.setAlignment(Qt.AlignTop) # 垂直顶部对齐
        # label.setAlignment(Qt.AlignBottom) # 垂直底部对齐
        # label.setAlignment(Qt.AlignVCenter) # 垂直居中对齐

        # label.setAlignment(Qt.AlignRight) # 水平右对齐
        # label.setAlignment(Qt.AlignHCenter) # 水平居中对齐
        # label.setAlignment(Qt.AlignLeft) # 水平左对齐

        # label.setAlignment(Qt.AlignHCenter | Qt.AlignTop) # 水平居中 & 垂直顶部
        # label.setAlignment(Qt.AlignHCenter | Qt.AlignBottom) # 水平居中 & 垂直底部
        # label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) # 水平居中 & 垂直居中
        label.setAlignment(Qt.AlignCenter) # 水平居中 & 垂直居中

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

67. PyQt5 图像 📷

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

        label = QLabel(self)
        label.setGeometry(0, 0, 250, 250)
        # label.setGeometry(x, y, 宽度, 高度)

        pixmap = QPixmap("profile_pic.jpg")
        label.setPixmap(pixmap)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

        label = QLabel(self)
        label.setGeometry(0, 0, 250, 250)
        # label.setGeometry(x, y, 宽度, 高度)

        pixmap = QPixmap("profile_pic.jpg")
        label.setPixmap(pixmap)

        label.setScaledContents(True)

        label.setGeometry((self.width() - label.width()) // 2, 
                          (self.height() - label.height()) // 2, 
                          label.width(), 
                          label.height())

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

68. PyQt5 布局管理器 🧲

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, 
                             QWidget, QVBoxLayout, QHBoxLayout, QGridLayout)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()        
        self.setGeometry(700, 300, 500, 500)
        self.initUI()
    
    def initUI(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        label1 = QLabel("#1", self)
        label2 = QLabel("#2", self)
        label3 = QLabel("#3", self)
        label4 = QLabel("#4", self)
        label5 = QLabel("#5", self)

        label1.setStyleSheet("background-color: red;")
        label2.setStyleSheet("background-color: yellow;")
        label3.setStyleSheet("background-color: green;")
        label4.setStyleSheet("background-color: blue;")
        label5.setStyleSheet("background-color: purple;")

        # vbox = QVBoxLayout()
        # vbox.addWidget(label1)
        # vbox.addWidget(label2)
        # vbox.addWidget(label3)
        # vbox.addWidget(label4)
        # vbox.addWidget(label5)
        # central_widget.setLayout(vbox)

        # hbox = QHBoxLayout()
        # hbox.addWidget(label1)
        # hbox.addWidget(label2)
        # hbox.addWidget(label3)
        # hbox.addWidget(label4)
        # hbox.addWidget(label5)
        # central_widget.setLayout(hbox)

        grid = QGridLayout()

        grid.addWidget(label1, 0, 0)
        grid.addWidget(label2, 0, 1)
        grid.addWidget(label3, 1, 0)
        grid.addWidget(label4, 1, 1)
        grid.addWidget(label5, 2, 2)

        central_widget.setLayout(grid)

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

69. PyQt5 按钮 🛎️

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(700, 300, 500, 500)  # 设置窗口位置和大小
        self.initUI()
    
    def initUI(self):
        pass

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(700, 300, 500, 500)  # 设置窗口位置和大小
        self.button = QPushButton("点击我!", self)  # 创建按钮
        self.initUI()
    
    def initUI(self):
        self.button.setGeometry(150, 200, 200, 100)  # 设置按钮位置和大小
        self.button.setStyleSheet("font-size: 30px;")  # 设置按钮字体大小
        self.button.clicked.connect(self.on_click)  # 连接按钮点击事件
    
    def on_click(self):
        print("按钮被点击!")
        self.button.setText("已点击!")  # 更改按钮文本
        self.button.setDisabled(True)  # 禁用按钮

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(700, 300, 500, 500)  # 设置窗口位置和大小
        self.button = QPushButton("点击我!", self)  # 创建按钮
        self.label = QLabel("你好", self)  # 创建标签
        self.initUI()
    
    def initUI(self):
        self.button.setGeometry(150, 200, 200, 100)  # 设置按钮位置和大小
        self.button.setStyleSheet("font-size: 30px;")  # 设置按钮字体大小
        self.button.clicked.connect(self.on_click)  # 连接按钮点击事件

        self.label.setGeometry(150, 300, 200, 100)  # 设置标签位置和大小
        self.label.setStyleSheet("font-size: 50px;")  # 设置标签字体大小
    
    def on_click(self):
        self.label.setText("再见")  # 点击按钮后更改标签文本

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

回到本系列的目录