June 5, 2022

变量是用于存储值的容器(字符串、整数、浮点数、布尔值)
变量的行为就像它所包含的值一样
# 字符串
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}")
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:.2f}")
# 将布尔值转换为'是'或'否'
print(f"管理员状态: {'是' if is_admin else '否'}") 类型转换 = 将变量从一种数据类型转换为另一种数据类型的过程
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一个提示用户输入数据的函数
将输入的数据作为字符串返回
name = input("你叫什么名字?: ")
age = int(input("你多大了?: "))
# age = int(age)
age = age + 1
print(f"你好 {name}!")
print("生日快乐")
print(f"你 {age} 岁了")练习 1 矩形面积计算器
length = float(input("输入长度: "))
width = float(input("输入宽度: "))
area = length * width
print(f"面积是: {area}平方厘米")
# Mac 上标2: Command + Control + Space, 在搜索栏中输入"上标"或"2"。或者 Option + v练习 2 购物车程序
item = input("你想买什么?: ")
price = float(input("价格是多少?: "))
quantity = int(input("你想要多少?: "))
total = price * quantity
print(f"你已购买 {quantity} 个 {item}")
print(f"你的总价是: ${total}")一个通过用随机词填空来创作故事的文字游戏
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}!")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 % 3x = 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.14import 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)}厘米") # 65.97# A = πr²
import math
radius = float(input('输入圆的半径: ')) # 10.5
area = math.pi * pow(radius, 2)
print(f"圆的面积是: {round(area, 2)}平方厘米") # 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只有在某个条件为真时才执行某些代码
否则执行其他代码
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("该物品不出售")online = False
if online:
print("该用户在线")
else:
print("该用户离线")逻辑运算符 = 评估多个条件(or, and, not)
or = 至少一个条件必须为真
and = 两个条件都必须为真
not = 反转条件(真或假)
# or
temp = 25
is_raining = False
if temp > 35 or temp < 0 or is_raining:
print("室外活动已取消")
else:
print("室外活动仍在进行")# and
temp = 20
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("今天天气不错👍")# not
temp = 25
is_sunny = True
if temp >= 28 and not is_sunny:
print("今天天气炎热☀️")
print("多喝水🥛")
elif temp <= 0 and not is_sunny:
print("今天天气寒冷❄️")
print("多穿点衣服🧥")条件表达式 = 一个单行的 if-else 语句快捷方式
如果条件为真则打印或返回其中一个值,否则打印或返回另一个值
X if 条件 else Y
num = 5
a = 6
b = 7
age = 13
temperature = 25
user_role = "admin"
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 "有限访问"name = input("输入你的全名: ")
# result = len(name)
# result = name.find("o")
# result = name.rfind("q")
# name = name.capitalize()
# name = name.upper()
# name = name.lower()
# result = name.isdigit()
# result = name.isalpha()
# phone_number = input("输入你的手机号码: ")
# result = phone_number.count("-")
# phone_number = phone_number.replace("-", " ")
# print(phone_number)
# 帮助验证用户输入
# 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}")索引 = 访问字符串的元素[开始:结束:步长]
开始 = 起始索引(包含)
结束 = 结束索引(不包含)
步长 = 访问字符串的步长大小
credit_number = "1234-5678-9012-3456"
print(credit_number[0])
print(credit_number[:4])
print(credit_number[5:9])
print(credit_number[5:])
print(credit_number[-1])
print(credit_number[::3])
last_digits = credit_number[-4:]
print(f"XXXX-XXXX-XXXX-{last_digits}")
credit_number = credit_number[::-1]
print(credit_number)格式化说明符 = {值:标志} 格式化值的显示方式
.(数字)f = 保留指定的小数位数(浮点数)
:(数字) = 分配指定的空格
:03 = 用零填充
:< = 左对齐
:> = 右对齐
:^ = 居中对齐
:+ = 使用加号表示正值
:= = 将符号放在最左边
: = 在正数前插入空格
:, = 逗号分隔符
price1 = 3.14159
price2 = -987.65
price3 = 12.34
print(f"价格 1 是 ${price1:.2f}")
print(f"价格 2 是 ${price2:.2f}")
print(f"价格 3 是 ${price3:.2f}")
print(f"价格 1 是 ${price1:10}")
print(f"价格 2 是 ${price2:10}")
print(f"价格 3 是 ${price3:10}")
print(f"价格 1 是 ${price1:010}")
print(f"价格 2 是 ${price2:010}")
print(f"价格 3 是 ${price3:010}")
print(f"价格 1 是 ${price1:<10}")
print(f"价格 2 是 ${price2:<10}")
print(f"价格 3 是 ${price3:<10}")
print(f"价格 1 是 ${price1:>10}")
print(f"价格 2 是 ${price2:>10}")
print(f"价格 3 是 ${price3:>10}")
print(f"价格 1 是 ${price1:^10}")
print(f"价格 2 是 ${price2:^10}")
print(f"价格 3 是 ${price3:^10}")
print(f"价格 1 是 ${price1:+}")
print(f"价格 2 是 ${price2:+}")
print(f"价格 3 是 ${price3:+}")
print(f"价格 1 是 ${price1:+,.2f}")
print(f"价格 2 是 ${price2:+,.2f}")
print(f"价格 3 是 ${price3:+,.2f}")
print(f"价格 1 是 ${price1: }")
print(f"价格 2 是 ${price2: }")
print(f"价格 3 是 ${price3: }")
print(f"价格 1 是 ${price1:,}")
print(f"价格 2 是 ${price2:,}")
print(f"价格 3 是 ${price3:,}")while 循环 = 在某个条件保持为真时执行某些代码
可能无限执行
name = input("输入你的名字: ")
while name == "":
print("你没有输入你的名字")
name = input("输入你的名字: ")
print(f"你好 {name}")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}")for 循环 = 执行固定次数的代码块
你可以遍历一系列值
for x in range(1, 11):
print(x)for x in reversed(range(1, 11)):
print(x)
print("新年快乐!")for x in range(1, 11, 2):
print(x)credit_card = "1234-5678-9012-3456"
for x in credit_card:
print(x)for x in range(1, 21):
if x == 13:
continue
else:
print(x)for x in range(1, 21):
if x == 13:
break
else:
print(x)嵌套循环 = 循环内的循环
外部循环:
内部循环:
for x in range(3):
for y in range(1, 10):
print(y, end="")
print()rows = int(input("输入行数: "))
columns = int(input("输入列数: "))
symbol = input("输入要使用的符号: ")
for x in range(rows):
for y in range(columns):
print(symbol, end="")
print()集合 = 包含多个元素的变量
列表 = [] 有序且可变。允许重复
集合 = {} 无序且不可变,但可以添加/删除。无重复
元组 = () 有序且不可变。允许重复。速度更快
# 列表
fruits = ["苹果", "橙子", "香蕉", "椰子"]
# print(fruits[0])
# print(fruits[:3])
# print(fruits[::2])
# print(fruits[::-1])
# for fruit in fruits:
# print(fruit)
# print(dir(fruits))
# print(help(fruits))
# print(len(fruits))
# print("苹果" in fruits)
# fruits[0] = "菠萝"
# fruits.append("菠萝")
# fruits.remove("苹果")
# fruits.insert(0, "菠萝")
# fruits.sort()
# fruits.reverse()
# fruits.clear()
# print(fruits.index("苹果"))
# print(fruits.count("香蕉"))# 集合
fruits = {"苹果", "橙子", "香蕉", "椰子"}
# print(fruits)
# print(dir(fruits))
# print(help(fruits))
# print(len(fruits))
# print("菠萝" in fruits)
# fruits.add("菠萝")
# fruits.remove("苹果")
# fruits.pop()
# fruits.clear()# 元组
fruits = ("苹果", "橙子", "香蕉", "椰子", "椰子")
# print(dir(fruits))
# print(help(fruits))
# print(len(fruits))
# print("菠萝" in fruits)
# print(fruits.index("苹果"))
# print(fruits.count("椰子"))
for fruit in fruits:
print(fruit)购物车程序
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=" ")
print()
for price in prices:
print(f"${price}", end=" ")
print()
for price in prices:
total += price
print(f"你的总价是: ${total}")2D 集合 = 列表的列表
fruits = ["苹果", "橙子", "香蕉", "椰子"]
vegetables = ["芹菜", "胡萝卜", "土豆"]
meats = ["鸡肉", "鱼肉", "火鸡"]
groceries = [fruits, vegetables, meats]
print(groceries)
print(groceries[0])
print(groceries[0][0])
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()字典 = 可变的键值对集合
无序,不允许重复,索引快速
capitals = {"美国": "华盛顿特区",
"印度": "新德里",
"中国": "北京",
"俄罗斯": "莫斯科"}
# print(dir(capitals))
# print(help(capitals))
# print(capitals.get("日本"))
# if capitals.get("俄罗斯"):
# print("该首都存在")
# else:
# print("该首都不存在")
# capitals.update({"德国":"柏林"})
# capitals.update({"美国":"底特律"})
# capitals.pop("中国")
# capitals.popitem()
# capitals.clear()
# keys = capitals.keys()
# for key in capitals.keys():
# print(key)
# values = capitals.values()
# for value in capitals.values():
# print(value)
items = capitals.items()
for key, value in capitals.items():
print(f"{key}: {value}")import random
# low = 1
# high = 100
# number = random.randint(low, high)
# number = random.random()
# options = ("石头", "剪刀", "布")
# option = random.choice(options)
# cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
# random.shuffle(cards)
# print(cards)Python 数字猜谜游戏
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} 之间选择一个数字")Python 石头剪刀布游戏
import random
options = ("石头", "剪刀", "布")
running = True
while running:
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 == "石头" and computer == "剪刀":
print("你赢了!")
elif player == "剪刀" and computer == "布":
print("你赢了!")
elif player == "布" and computer == "石头":
print("你赢了!")
else:
print("你输了!")
if not input("再玩一次?(y/n): ").lower() == "y":
running = False
print("感谢游戏!")函数 = 一个可重用的代码块
将相关语句放在一组中
可以在被调用时执行
有利于模块化和代码重用
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 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))
print(subtract(1, 2))
print(multiply(1, 2))
print(divide(1, 2))def create_name(first, last):
first = first.capitalize()
last = last.capitalize()
return first + " " + last
full_name = create_name("spongebob", "squarepants")
print(full_name)默认参数 = 如果缺少参数则使用的默认值
使参数可选
import time
def net_price(list_price, discount=0, tax=0.05):
return list_price * (1 - discount) * (1 + tax)
# print(net_price(500))
# print(net_price(500, 0.1))
print(net_price(500, 0.1, 0))def count(end, start=0):
for x in range(start, end + 1):
print(x)
time.sleep(1)
print("完成!")
count(30, 15)关键字参数 = 参数前面有一个标识符
有助于提高代码的可读性
参数的顺序无关紧要
def hello(greeting, title, first, last):
print(f"{greeting} {title}{first} {last}")
hello("你好", title="先生.", last="代码", first="Bro")for number in range(1, 11):
print(number, end=" ")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)*args = 允许你将多个非键值参数传递给函数
.unpack() 函数
将值解包为元组
def add(*args):
total = 0
for arg in args:
total += arg
return total
print(add(1, 2, 3, 4))def display_name(*args):
print(f"你好", end=" ")
for arg in args:
print(arg, end=" ")
display_name("Dr.", "Spongebob", "Harold", "Squarepants", "III")**kwargs = 允许你将多个关键字参数传递给函数
.unpack() 函数
将值解包为字典
def print_address(**kwargs):
for key, value in kwargs.items():
print(f"{key:12} {value}")
print_address(街道="123 假街",
公寓="100",
城市="底特律",
州="MI",
邮编="54321")def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
# for value in kwargs.values():
# print(value, end=" ")
if "公寓" in kwargs:
print(f"{kwargs.get('街道')} {kwargs.get('公寓')}")
elif "邮政信箱" in kwargs:
print(f"{kwargs.get('邮政信箱')}")
else:
print(f"{kwargs.get('街道')}")
print(f"{kwargs.get('城市')}, {kwargs.get('州')} {kwargs.get('邮编')}")
shipping_label("Dr.", "Spongebob", "Squarepants",
街道="123 假街",
邮政信箱="PO box #1001",
城市="底特律",
州="MI",
邮编="54321")迭代器 = 一个对象,它以惰性方式计算/返回其下一个值
迭代器能够连续工作以避免存储所有数据
好处 = 内存高效且无限
# 常规 for 循环
my_list = [1, 2, 3, 4, 5]
for num in my_list:
print(num)# 使用迭代器
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))# 无限迭代器
my_numbers = iter([1, 2, 3, 4, 5])
for num in my_numbers:
print(num)成员运算符 = 用于测试对象或字符串是否在集合中找到
(字符串、列表、元组、集合或字典)
word = "APPLE"
letter = input("猜测集合中的一个字母: ")
if letter in word:
print(f"有一个 {letter}")
else:
print(f"{letter} 未找到")students = {"海绵宝宝", "派大星", "章鱼哥"}
student = input("输入学生姓名: ")
if student in students:
print(f"{student} 在这个班级")
else:
print(f"{student} 不在这个班级")grades = {"海绵宝宝": "C",
"派大星": "F",
"章鱼哥": "D"}
student = input("输入学生姓名: ")
if student in grades:
print(f"{student} 的成绩是 {grades[student]}")
else:
print(f"{student} 未找到在成绩单中")email = "BroCode@gmail.com"
if "@" in email and "." in email:
print("有效邮箱")
else:
print("无效邮箱")列表推导式 = 简洁的创建列表的方式[表达式 for 值 in 可迭代对象 if 条件]
更快且使用更少的代码
# doubles = []
# for x in range(1, 11):
# doubles.append(x * 2)
# print(doubles)
doubles = [x * 2 for x in range(1, 11)]
triples = [y * 3 for y in range(1, 11)]
squares = [z * z for z in range(1, 11)]# fruits = ["苹果", "橙子", "香蕉", "椰子"]
# fruits = [fruit.upper() for fruit in fruits]
# fruit_chars = [fruit[0] for fruit in fruits]
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)
print(negative_nums)
print(even_nums)
print(odd_nums)grades = [85, 42, 79, 90, 56, 61, 30]
passing_grades = [grade for grade in grades if grade >= 60]
print(passing_grades)匹配语句 = Python 3.10+ 中 switch 的替代品
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))
print(day_of_week(2))def is_weekend(day):
match day:
case "星期六" | "星期日":
return True
case "星期一" | "星期二" | "星期三" | "星期四" | "星期五":
return False
case _:
return False
print(is_weekend("星期六"))模块 = 包含 Python 代码的文件(.py)
用于将相关代码分组为模块
模块是可重用且导入的
# import messages as msg # 别名
# from messages import hello, bye # 单独导入
import messages
messages.hello()
messages.bye()# 示例 example.py
def hello():
print("吃了吗?")
def bye():
print("回见!")# 导入示例
import example
example.hello()
example.bye()作用域 = 变量在哪里可见和可访问
作用域解析 = (LEGB) 局部 -> 封闭 -> 全局 -> 内置
from math import e
x = 1 # 全局
def func1():
x = 2 # 封闭
print(x) # 2
def func2():
x = 3 # 局部
print(x) # 3
func2()
func1()
print(x)
print(e)# Python 文件可以作为可重用模块或独立程序
# __name__ = 一个特殊变量,如果程序是主程序则设置为 '__main__'
# 例如 if __name__ == '__main__':
# 这将使我们决定运行一个模块是否,或导入它
def main():
print("你好")
print("再见")
if __name__ == '__main__':
main()import time
# print(time.ctime(0)) # 将时间转换为字符串
# print(time.time()) # 返回自纪元以来的当前秒数
# print(time.ctime(time.time())) # 返回当前时间
time_object = time.localtime() # 返回当前时间对象
# time_object = time.gmtime()
local_time = time.strftime("%B %d %Y %H:%M:%S", time_object)
print(local_time)
time_string = "20 April, 2020"
time_object = time.strptime(time_string, "%d %B, %Y")
print(time_object)
# (年, 月, 日, 小时, 分钟, 秒, 周中第几天, 年中第几天, dst)
time_tuple = (2020, 4, 20, 4, 20, 0, 0, 0, 0)
time_string = time.asctime(time_tuple)
# time_string = time.mktime(time_tuple)
print(time_string)线程 = 流程中执行的流
多任务 = 同时完成许多任务(非线性)
多线程 = 同时执行多个线程
释放 GIL(全局解释器锁)
线程对于 I/O 任务和高级别任务非常有用
CPU 密集型任务:使用多处理
import threading
import time
def eat_breakfast():
time.sleep(3)
print("你吃了早餐")
def drink_coffee():
time.sleep(4)
print("你喝了咖啡")
def study():
time.sleep(5)
print("你学习了")
x = threading.Thread(target=eat_breakfast, args=())
x.start()
y = threading.Thread(target=drink_coffee, args=())
y.start()
z = threading.Thread(target=study, args=())
z.start()
# eat_breakfast()
# drink_coffee()
# study()
x.join()
y.join()
z.join()
print(threading.active_count())
print(threading.enumerate())
print(time.perf_counter())守护线程 = 在主程序结束时运行的线程
非守护线程在退出前无法被杀死
例如:后台任务、垃圾回收、等待输入、长时间运行的进程
import threading
import time
def timer():
print()
count = 0
while True:
time.sleep(1)
count += 1
print("已登录: ", count, "秒")
x = threading.Thread(target=timer, daemon=True)
x.start()
# x.setDaemon(True)
# print(x.isDaemon())
answer = input("你想退出吗?")多处理 = 使用多个 CPU 同时运行任务
更好地用于 CPU 密集型任务(繁重的计算)
多线程 = 使用多个线程同时运行任务
更好地用于 I/O 密集型任务(等待输入/输出)
GIL:全局解释器锁,(一次只允许一个线程保持 CPU 的控制权)
CPU 密集型任务更好地使用多处理
from multiprocessing import Process, cpu_count
import time
def counter(num):
count = 0
while count < num:
count += 1
def main():
print(cpu_count())
a = Process(target=counter, args=(500000000,))
b = Process(target=counter, args=(500000000,))
a.start()
b.start()
print("正在处理...")
a.join()
b.join()
print("完成!")
print("完成时间:", time.perf_counter(), "秒")
if __name__ == '__main__':
main()函数到对象 = 调用一个函数
并将其作为参数传递给另一个函数
也称为高阶函数
def loud(text):
return text.upper()
def quiet(text):
return text.lower()
def hello(func):
text = func("你好")
print(text)
hello(loud)
hello(quiet)高阶函数 = 一个函数
或
(在 Python 中,函数也是对象)
def loud(text):
return text.upper()
def quiet(text):
return text.lower()
def hello(func):
text = func("你好")
print(text)
hello(loud)
hello(quiet)def divisor(x):
def dividend(y):
return y / x
return dividend
divide = divisor(2)
print(divide(10))lambda 函数 = 小型匿名函数
单行函数
lambda 参数:表达式
# def double(x):
# return x * 2
double = lambda x: x * 2
multiply = lambda x, y: x * y
add = lambda x, y, z: x + y + z
full_name = lambda first_name, last_name: first_name + " " + last_name
age_check = lambda age: True if age >= 18 else False
print(double(5))
print(multiply(5, 6))
print(add(5, 6, 7))
print(full_name("海绵", "宝宝"))
print(age_check(18))sort() 方法 = 用于列表
sort() 函数 = 用于迭代对象
# students = ["章鱼哥", "海绵宝宝", "派大星", "珊迪"]
# students.sort(reverse=True)
# for i in students:
# print(i)
# sorted_students = sorted(students, reverse=True)
# for i in sorted_students:
# print(i)students = [("章鱼哥", "F", 60),
("海绵宝宝", "A", 33),
("派大星", "D", 36),
("珊迪", "B", 21)]
grade = lambda grades: grades[1]
# students.sort(key=grade, reverse=True)
sorted_students = sorted(students, key=grade)
for i in sorted_students:
print(i)students = (("章鱼哥", "F", 60),
("海绵宝宝", "A", 33),
("派大星", "D", 36),
("珊迪", "B", 21))
age = lambda ages: ages[2]
sorted_students = sorted(students, key=age)
for i in sorted_students:
print(i)map() = 对可迭代对象中的每个项应用函数
map(函数, 可迭代对象)
store = [("衬衫", 20.00),
("裤子", 25.00),
("夹克", 50.00),
("袜子", 10.00)]
to_euros = lambda data: (data[0], data[1] * 0.82)
to_dollars = lambda data: (data[0], data[1] / 0.82)
store_euros = list(map(to_euros, store))
store_dollars = list(map(to_dollars, store))
for i in store_euros:
print(i)filter() = 从集合中创建项的集合
对于函数返回 True
filter(函数, 可迭代对象)
friends = [("Rachel", 19),
("Monica", 18),
("Phoebe", 17),
("Joey", 14),
("Chandler", 21),
("Ross", 21)]
age = lambda data: data[1] >= 18
drinking_buddies = list(filter(age, friends))
for i in drinking_buddies:
print(i)reduce() = 对可迭代对象应用函数并将其减少为单个累积值
对成对执行函数
reduce(函数, 可迭代对象)
import functools
letters = ["H", "E", "L", "L", "O"]
word = functools.reduce(lambda x, y: x + y, letters)
print(word)import functools
factorial = [5, 4, 3, 2, 1]
result = functools.reduce(lambda x, y: x * y, factorial)
print(result)异常 = 在程序执行期间发生中断流程的事件
(ZeroDivisionError, TypeError, ValueError 等)
try:
except:
finally:
try:
numerator = int(input("输入一个除数: "))
denominator = int(input("输入一个除数: "))
result = numerator / denominator
except ZeroDivisionError as e:
print(e)
print("不能除以零傻瓜!")
except ValueError as e:
print(e)
print("只输入数字傻瓜!")
except Exception as e:
print(e)
print("出错了!")
else:
print(result)
finally:
print("这将始终执行")import os
path = "/Users/yuuniji/Desktop/test"
if os.path.exists(path):
print("该位置存在!")
if os.path.isfile(path):
print("那是一个文件")
elif os.path.isdir(path):
print("那是一个目录!")
else:
print("该位置不存在!")Python 写入文件(.txt .json .csv)
# txt = "Yo\nThis is some text\nHave a good one!\n"
# with open('/Users/yuuniji/Desktop/test.txt', 'w') as file:
# file.write(txt)
# print("已写入")import json
employee = {
"name": "海绵宝宝",
"age": 30,
"job": "厨师"
}
file_path = "/Users/yuuniji/Desktop/employee.json"
with open(file_path, 'w') as file:
json.dump(employee, file, indent=4)
print("已写入")import csv
employees = [["Name", "Age", "Job"],
["海绵宝宝", "30", "厨师"],
["派大星", "35", "无业"],
["章鱼哥", "28", "收银员"]]
file_path = "/Users/yuuniji/Desktop/employees.csv"
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
for row in employees:
writer.writerow(row)
print("已写入")Python 读取文件(.txt .json .csv)
# file_path = "/Users/yuuniji/Desktop/test.txt"
# with open(file_path, 'r') as file:
# content = file.read()
# print(content)import json
file_path = "/Users/yuuniji/Desktop/employee.json"
with open(file_path, 'r') as file:
content = json.load(file)
print(content["name"])import csv
file_path = "/Users/yuuniji/Desktop/employees.csv"
with open(file_path, 'r') as file:
content = csv.reader(file)
for line in content:
print(line[0])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")
print(now)
target_datetime = datetime.datetime(2030, 1, 2, 12, 30, 1)
current_datetime = datetime.datetime.now()
if target_datetime < current_datetime:
print("目标日期已过")
else:
print("目标日期还未到")GUI = 图形用户界面
PyQt5 = 一个用于 Python 的 GUI 模块
Widgets = GUI 元素(按钮、文本框、标签、图片等)
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
def main():
app = QApplication(sys.argv)
window = QMainWindow()
window.setGeometry(700, 300, 500, 500)
window.setWindowTitle("Yuuniji 的 GUI")
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: #A23BEC;"
"background-color: #F3FF33;"
"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.AlignLeft)
# label.setAlignment(Qt.AlignHCenter)
# label.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
label.setAlignment(Qt.AlignCenter)
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)
pixmap = QPixmap("logo.png")
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()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)
# hbox = QHBoxLayout()
# hbox.addWidget(label1)
# hbox.addWidget(label2)
# hbox.addWidget(label3)
# hbox.addWidget(label4)
# hbox.addWidget(label5)
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, 0, 1, 2)
central_widget.setLayout(grid)
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, 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):
print("按钮被点击")
self.button.setDisabled(True)
self.label.setText("再见")
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, QCheckBox
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.checkbox = QCheckBox("我同意", self)
self.initUI()
def initUI(self):
self.checkbox.setGeometry(10, 0, 500, 100)
self.checkbox.setStyleSheet("font-size: 30px;"
"font-family: Arial;")
# self.checkbox.setChecked(True)
self.checkbox.stateChanged.connect(self.checkbox_changed)
def checkbox_changed(self, state):
if state == Qt.Checked:
print("你同意")
else:
print("你不同意")
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, QRadioButton, QButtonGroup
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.radio1 = QRadioButton("Visa", self)
self.radio2 = QRadioButton("Mastercard", self)
self.radio3 = QRadioButton("礼品卡", self)
self.radio4 = QRadioButton("店内", self)
self.radio5 = QRadioButton("网上", self)
self.button_group1 = QButtonGroup()
self.button_group2 = QButtonGroup()
self.initUI()
def initUI(self):
self.radio1.setGeometry(0, 0, 300, 50)
self.radio2.setGeometry(0, 50, 300, 50)
self.radio3.setGeometry(0, 100, 300, 50)
self.radio4.setGeometry(0, 150, 300, 50)
self.radio5.setGeometry(0, 200, 300, 50)
self.setStyleSheet("QRadioButton{"
"font-size: 40px;"
"font-family: Arial;"
"padding: 10px;"
"}")
self.button_group1.addButton(self.radio1)
self.button_group1.addButton(self.radio2)
self.button_group1.addButton(self.radio3)
self.button_group2.addButton(self.radio4)
self.button_group2.addButton(self.radio5)
self.radio1.toggled.connect(self.radio_button_changed)
self.radio2.toggled.connect(self.radio_button_changed)
self.radio3.toggled.connect(self.radio_button_changed)
self.radio4.toggled.connect(self.radio_button_changed)
self.radio5.toggled.connect(self.radio_button_changed)
def radio_button_changed(self):
radio_button = self.sender()
if radio_button.isChecked():
print(f"{radio_button.text()} 被选中")
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, QLineEdit, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.line_edit = QLineEdit(self)
self.button = QPushButton("提交", self)
self.initUI()
def initUI(self):
self.line_edit.setGeometry(10, 10, 200, 40)
self.line_edit.setStyleSheet("font-size: 25px;"
"font-family: Arial;")
self.line_edit.setPlaceholderText("输入用户名")
# self.line_edit.setEchoMode(QLineEdit.Password)
self.button.setGeometry(220, 10, 100, 40)
self.button.setStyleSheet("font-size: 25px;"
"font-family: Arial;")
self.button.clicked.connect(self.submit)
def submit(self):
text = self.line_edit.text()
print(f"你输入了: {text}")
self.line_edit.clear()
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, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.button1 = QPushButton("#1", self)
self.button2 = QPushButton("#2", self)
self.button3 = QPushButton("#3", self)
self.initUI()
def initUI(self):
self.button1.setGeometry(10, 10, 100, 100)
self.button2.setGeometry(120, 10, 100, 100)
self.button3.setGeometry(230, 10, 100, 100)
self.button1.setObjectName("button1")
self.button2.setObjectName("button2")
self.button3.setObjectName("button3")
self.setStyleSheet("""
QPushButton{
font-size: 40px;
font-family: Arial;
padding: 15px 75px;
border: 3px solid;
border-radius: 15px;
}
QPushButton#button1{
background-color: #FF6EC7;
}
QPushButton#button1:hover{
background-color: #E856B4;
}
QPushButton#button2{
background-color: #A06EFF;
}
QPushButton#button2:hover{
background-color: #8E52E8;
}
QPushButton#button3{
background-color: #6EFFC7;
}
QPushButton#button3:hover{
background-color: #5CE8AF;
}
""")
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()使用 PyQt5 的 Python 数字时钟 GUI
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtCore import QTimer, QTime, Qt
from PyQt5.QtGui import QFont, QFontDatabase
class DigitalClock(QWidget):
def __init__(self):
super().__init__()
self.time_label = QLabel(self)
self.timer = QTimer(self)
self.initUI()
def initUI(self):
self.setWindowTitle("数字时钟")
self.setGeometry(600, 400, 300, 100)
vbox = QVBoxLayout()
vbox.addWidget(self.time_label)
self.setLayout(vbox)
self.time_label.setAlignment(Qt.AlignCenter)
self.time_label.setStyleSheet("font-size: 150px;"
"color: hsl(111, 100%, 50%);")
self.setStyleSheet("background-color: black;")
font_id = QFontDatabase.addApplicationFont("DS-DIGIT.TTF")
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
my_font = QFont(font_family, 150)
self.time_label.setFont(my_font)
self.timer.timeout.connect(self.update_time)
self.timer.start(1000)
self.update_time()
def update_time(self):
current_time = QTime.currentTime().toString("hh:mm:ss AP")
self.time_label.setText(current_time)
if __name__ == "__main__":
app = QApplication(sys.argv)
clock = DigitalClock()
clock.show()
sys.exit(app.exec_())使用 PyQt5 的 Python 秒表 GUI
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QPushButton, QVBoxLayout, QHBoxLayout)
from PyQt5.QtCore import QTimer, QTime, Qt
class Stopwatch(QWidget):
def __init__(self):
super().__init__()
self.time = QTime(0, 0, 0, 0)
self.time_label = QLabel("00:00:00.00", self)
self.start_button = QPushButton("开始", self)
self.stop_button = QPushButton("停止", self)
self.reset_button = QPushButton("重置", self)
self.timer = QTimer(self)
self.initUI()
def initUI(self):
self.setWindowTitle("秒表")
vbox = QVBoxLayout()
vbox.addWidget(self.time_label)
self.setLayout(vbox)
self.time_label.setAlignment(Qt.AlignCenter)
hbox = QHBoxLayout()
hbox.addWidget(self.start_button)
hbox.addWidget(self.stop_button)
hbox.addWidget(self.reset_button)
vbox.addLayout(hbox)
self.setStyleSheet("""
QPushButton, QLabel{
padding: 20px;
font-weight: bold;
font-family: calibri;
}
QPushButton{
font-size: 50px;
}
QLabel{
font-size: 120px;
background-color: hsl(200, 100%, 85%);
border-radius: 20px;
}
""")
self.start_button.clicked.connect(self.start)
self.stop_button.clicked.connect(self.stop)
self.reset_button.clicked.connect(self.reset)
self.timer.timeout.connect(self.update_display)
def start(self):
self.timer.start(10)
def stop(self):
self.timer.stop()
def reset(self):
self.timer.stop()
self.time = QTime(0, 0, 0, 0)
self.time_label.setText(self.format_time(self.time))
def format_time(self, time):
hours = time.hour()
minutes = time.minute()
seconds = time.second()
milliseconds = time.msec() // 10
return f"{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:02}"
def update_display(self):
self.time = self.time.addMSecs(10)
self.time_label.setText(self.format_time(self.time))
if __name__ == "__main__":
app = QApplication(sys.argv)
stopwatch = Stopwatch()
stopwatch.show()
sys.exit(app.exec_())使用 PyQt5 的 Python 天气应用 GUI
import sys
import requests
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QLineEdit, QPushButton, QVBoxLayout)
from PyQt5.QtCore import Qt
class WeatherApp(QWidget):
def __init__(self):
super().__init__()
self.city_label = QLabel("输入城市名称: ", self)
self.city_input = QLineEdit(self)
self.get_weather_button = QPushButton("获取天气", self)
self.temperature_label = QLabel(self)
self.emoji_label = QLabel(self)
self.description_label = QLabel(self)
self.initUI()
def initUI(self):
self.setWindowTitle("天气应用")
vbox = QVBoxLayout()
vbox.addWidget(self.city_label)
vbox.addWidget(self.city_input)
vbox.addWidget(self.get_weather_button)
vbox.addWidget(self.temperature_label)
vbox.addWidget(self.emoji_label)
vbox.addWidget(self.description_label)
self.setLayout(vbox)
self.city_label.setAlignment(Qt.AlignCenter)
self.city_input.setAlignment(Qt.AlignCenter)
self.temperature_label.setAlignment(Qt.AlignCenter)
self.emoji_label.setAlignment(Qt.AlignCenter)
self.description_label.setAlignment(Qt.AlignCenter)
self.city_label.setObjectName("city_label")
self.city_input.setObjectName("city_input")
self.get_weather_button.setObjectName("get_weather_button")
self.temperature_label.setObjectName("temperature_label")
self.emoji_label.setObjectName("emoji_label")
self.description_label.setObjectName("description_label")
self.setStyleSheet("""
QLabel, QPushButton{
font-family: Arial;
}
QLabel#city_label{
font-size: 40px;
font-style: italic;
}
QLineEdit#city_input{
font-size: 40px;
}
QPushButton#get_weather_button{
font-size:30px;
font-weight: bold;
}
QLabel#temperature_label{
font-size: 75px;
}
QLabel#emoji_label{
font-size: 100px;
font-family: Segoe UI Emoji;
}
QLabel#description_label{
font-size: 50px;
}
""")
self.get_weather_button.clicked.connect(self.get_weather)
def get_weather(self):
api_key = "你的_API_密钥"
city = self.city_input.text()
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data["cod"] == 200:
self.display_weather(data)
except requests.exceptions.HTTPError as http_error:
match response.status_code:
case 400:
self.display_error("错误请求:\n请检查你的输入")
case 401:
self.display_error("未授权:\nAPI 密钥不正确")
case 403:
self.display_error("禁止:\n访问被拒绝")
case 404:
self.display_error("未找到:\n城市未找到")
case 500:
self.display_error("内部服务器错误:\n请稍后再试")
case 502:
self.display_error("错误网关:\n服务器响应无效")
case 503:
self.display_error("服务不可用:\n服务器宕机")
case 504:
self.display_error("网关超时:\n服务器无响应")
case _:
self.display_error(f"HTTP 错误发生:\n{http_error}")
except requests.exceptions.ConnectionError:
self.display_error("连接错误:\n检查你的网络连接")
except requests.exceptions.Timeout:
self.display_error("超时错误:\n请求超时")
except requests.exceptions.TooManyRedirects:
self.display_error("重定向过多:\n检查 URL")
except requests.exceptions.RequestException as req_error:
self.display_error(f"请求错误:\n{req_error}")
def display_error(self, message):
self.temperature_label.setStyleSheet("font-size: 30px;")
self.temperature_label.setText(message)
self.emoji_label.clear()
self.description_label.clear()
def display_weather(self, data):
self.temperature_label.setStyleSheet("font-size: 75px;")
temperature_k = data["main"]["temp"]
temperature_c = temperature_k - 273.15
temperature_f = (temperature_k * 9/5) - 459.67
weather_id = data["weather"][0]["id"]
weather_description = data["weather"][0]["description"]
self.temperature_label.setText(f"{temperature_c:.0f}°C")
self.emoji_label.setText(self.get_weather_emoji(weather_id))
self.description_label.setText(weather_description)
@staticmethod
def get_weather_emoji(weather_id):
if 200 <= weather_id <= 232:
return "🌩️"
elif 300 <= weather_id <= 321:
return "🌦️"
elif 500 <= weather_id <= 531:
return "🌧️"
elif 600 <= weather_id <= 622:
return "❄️"
elif 701 <= weather_id <= 741:
return "🌫️"
elif weather_id == 762:
return "🌋"
elif weather_id == 771:
return "💨"
elif weather_id == 781:
return "🌪️"
elif weather_id == 800:
return "☀️"
elif 801 <= weather_id <= 804:
return "☁️"
else:
return ""
if __name__ == '__main__':
app = QApplication(sys.argv)
weather_app = WeatherApp()
weather_app.show()
sys.exit(app.exec_())HTTP 响应状态码
HTTP 响应状态码指示特定的 HTTP 请求是否已成功完成。响应分为五类:
400 错误请求
由于被认为是客户端错误的某些原因(例如,格式错误的请求语法、无效的请求消息帧或欺骗性请求路由),服务器无法或不会处理该请求。
401 未授权
尽管 HTTP 标准指定”未授权”,但从语义上讲,此响应意味着”未经身份验证”。也就是说,客户端必须对自己进行身份验证才能获得请求的响应。
403 禁止
客户端没有访问内容的权限;也就是说,它是未经授权的,因此服务器拒绝提供请求的资源。与 401 未授权 不同,客户端的身份是服务器已知的。
404 未找到
服务器找不到请求的资源。在浏览器中,这意味着无法识别 URL。在 API 中,这也可能意味着端点有效但资源本身不存在。服务器也可能发送此响应而不是 403 禁止,以向未经授权的客户端隐藏资源的存在。由于其在网络上的频繁出现,此响应代码可能是最著名的。
服务器错误响应
500 内部服务器错误
服务器遇到了它不知道如何处理的情况。
502 错误网关
此错误响应意味着服务器在充当网关以获取处理请求所需的响应时,得到了无效响应。
503 服务不可用
服务器尚未准备好处理请求。常见原因是服务器正在进行维护或过载。请注意,与此响应一起,应发送一个用户友好的页面来解释问题。此响应应用于临时条件,并且如果可能,Retry-After HTTP 标头应包含服务恢复的估计时间。网站管理员还必须注意与此响应一起发送的与缓存相关的标头,因为这些临时条件响应通常不应被缓存。
504 网关超时
当服务器充当网关且无法及时获得响应时,会给出此错误响应。
exception requests.ConnectionError(*args, **kwargs)
发生连接错误。
exception requests.Timeout(*args, **kwargs)
请求超时。
捕获此错误将同时捕获 ConnectTimeout 和 ReadTimeout 错误。
exception requests.TooManyRedirects(*args, **kwargs)
重定向过多。
exception requests.RequestException(*args, **kwargs)
处理你的请求时发生了模糊的异常。