# 水仙花数
水仙花数,即一个三位数,其各位数字的立方和等于该数本身。例如:153 = 1^3 + 5^3 + 3^3。找出所有的水仙花数并打印出来。
def ques1(): | |
for i in range(1, 1000): | |
num = i | |
sum_of_cubes = 0 | |
while num > 0: | |
digit = num % 10 | |
sum_of_cubes += digit ** 3 | |
num //= 10 | |
if sum_of_cubes == i: | |
print(f"{i}是一个水仙花数。") | |
if __name__ == "__main__": | |
ques1() |
# 手机号码数字表格
手机号码数字表格,将用户输入的手机号码的每个数字重复打印 9 次,形成一个表格。
def ques2(): | |
phone_number = input("请输入手机号码:\n") | |
for digit in phone_number: | |
print(str(digit + "\t")*9) | |
if __name__ == "__main__": | |
ques2() |
# 最大质数
找出小于用户输入的正整数 n 的最大质数并打印出来。
def ques3(): | |
n = int(input("请输入一个大于1的正整数n:\n")) | |
for i in reversed(range(3, n)): | |
is_prime = True | |
for j in range(2, int(i**0.5) + 1): | |
if i % j == 0: | |
is_prime = False | |
break | |
if is_prime: | |
print(f"{i}是小于{n}的最大质数。") | |
break | |
if __name__ == "__main__": | |
ques3() |
# 99 乘法表
打印 99 乘法表。
def ques4(): | |
for i in range(1, 10): | |
for j in range(1, 10): | |
print(f"{i}x{j}={i*j}\t", end="") | |
print() | |
if __name__ == "__main__": | |
ques4() |
# 猜数游戏
猜数游戏,程序随机生成一个 1 到 100 之间的整数,用户输入猜测的数字,程序提示猜测结果(太大、太小或猜对),并统计猜测次数,直到用户猜对为止。
from random import * | |
def ques5(): | |
ans = randint(1, 100) | |
attempts = 0 | |
print("欢迎来到猜数字游戏!") | |
while True: | |
guess = input("请输入你猜的数字(1-100),或输入0退出游戏:") | |
if guess == '0': | |
print("已退出游戏,欢迎下次再来!") | |
break | |
if not guess.isdigit() or int(guess) < 0 or int(guess) > 100: | |
print("输入有误,请输入1到100之间的数字,或输入0退出游戏。") | |
continue | |
guess = int(guess) | |
if guess == ans: | |
attempts += 1 | |
print(f"恭喜你,猜对了!你一共猜了{attempts}次。") | |
else: | |
attempts += 1 | |
if guess < ans: | |
print("你猜的数字太小了,请再试一次。") | |
else: | |
print("你猜的数字太大了,请再试一次。") | |
if __name__ == "__main__": | |
ques5() |
# 区域回文素数
找出用户指定范围内的所有回文素数并打印出来。
def ques6(): | |
def palindrome(x): | |
x = str(x) | |
re = "".join(list(reversed(x))) | |
if x == re: | |
return True | |
else: | |
return False | |
def prime(x): | |
if x < 2: | |
return False | |
for i in range(2, x): | |
if x % i == 0: | |
return False | |
return True | |
print("请给出一个范围区间,我将输出这个区间中所有回文素数") | |
start = int(input("起始值:")) | |
end = int(input("结束值:")) | |
for i in range(start, end + 1): | |
if palindrome(i) and prime(i): | |
print(str(i) + "是回文素数") | |
if __name__ == "__main__": | |
ques6() |
# 数字和最大字符串
找出下列列表中,字符串中数字和最大的字符串,并打印出来。
列表:['a1b23', 'nodigits', 'c7d3e11', 'x5y4t']。
def ques7(): | |
source = ['a1b23', 'nodigits', 'c7d3e11', 'x5y4t'] | |
def sum_of_digits(s): | |
sumValue = 0 | |
for k in s: | |
if k.isdigit(): | |
sumValue += int(k) | |
return sumValue | |
max_string = max(source, key=lambda s: sum_of_digits(s)) | |
print(f"字符串中数字和最大的字符串是:{max_string}") | |
if __name__ == "__main__": | |
ques7() |
# 华氏度转换
将摄氏温度转换为华氏温度,使用 map 函数对一组摄氏温度进行转换,并打印出转换后的华氏温度列表。
temper = [0, 10, 25, 30, 100]。
转换公式:fff = temper * 9 / 5 + 32
def ques8(): | |
temper = [0, 10, 25, 30, 100] | |
def change(temper): | |
fff = temper * 9 / 5 + 32 | |
return fff | |
results = list(map(lambda x: change(x), temper)) | |
print(results) | |
if __name__ == "__main__": | |
ques8() |
# 简单计算器
设计一个简单的计算器,分别用函数实现加法、减法、乘法和除法运算。
def ques9(): | |
def display_menu(): | |
print("欢迎使用简单计算器!") | |
print("请选择运算类型:") | |
print("1. 加法") | |
print("2. 减法") | |
print("3. 乘法") | |
print("4. 除法") | |
print("5. 退出") | |
do = input() | |
return do | |
def add(a, b): | |
return a + b | |
def subtract(a, b): | |
return a - b | |
def multiply(a, b): | |
return a * b | |
def divide(a, b): | |
if b == 0: | |
return "错误:除数不能为零。" | |
return a / b | |
def get_numbers(): | |
x = input("请输入第一个数字:") | |
num1 = float(x) | |
y = input("请输入第二个数字:") | |
num2 = float(y) | |
return num1, num2, x, y | |
def calculate(num1, num2, x, y, do): | |
if do == '1': | |
result = add(num1, num2) | |
print(f"{x} + {y} = {result}") | |
elif do == '2': | |
result = subtract(num1, num2) | |
print(f"{x} - {y} = {result}") | |
elif do == '3': | |
result = multiply(num1, num2) | |
print(f"{x} * {y} = {result}") | |
elif do == '4': | |
result = divide(num1, num2) | |
if result == "错误:除数不能为零。": | |
print(result) | |
else: | |
print(f"{x} / {y} = {result}") | |
else: | |
print("输入有误,请重新启动计算器。") | |
do = display_menu() | |
if do == '5': | |
print("已退出计算器,欢迎下次再来!") | |
return | |
num1, num2, x, y = get_numbers() | |
calculate(num1, num2, x, y, do) | |
if __name__ == "__main__": | |
ques9() |
# 猜拳游戏
猜拳游戏,包含普通模式、困难模式和简单模式,玩家可选择模式进行游戏,并统计总局数和玩家获胜局数,玩家可随时退出游戏,程序结束时显示统计结果。
普通模式:电脑随机出拳。困难模式:电脑有 80% 的概率出能赢玩家的拳。简单模式:电脑有 70% 的概率出能输给玩家的拳。游戏规则:剪刀(0)胜布(2),布(2)胜石头(1),石头(1)胜剪刀(0)。
电脑出拳策略根据玩家选择的模式进行调整。
from random import * | |
def ques10(): | |
total_game = 0 | |
player_wins = 0 | |
mode = 'normal' | |
print("欢迎来到猜拳游戏!\n") | |
print("="*50) | |
user_input = input("选择游戏模式\n1-普通模式\n2-困难模式\n3-简单模式\n0-退出游戏\n请输入数字选择模式:\n") | |
if user_input == '2': | |
mode = 'hard' | |
print("已选择困难模式!\n") | |
elif user_input == '3': | |
mode = 'easy' | |
print("已选择简单模式!\n") | |
elif user_input == '0': | |
print("已退出游戏,欢迎下次再来!") | |
exit() | |
else: | |
print("已选择普通模式!\n") | |
while True: | |
x = input("请出拳:剪刀(0)、石头(1)、布(2)、退出游戏(3)\n") | |
if x == '3': | |
print("已退出游戏,欢迎下次再来!") | |
break | |
elif x not in ['0', '1', '2']: | |
print("输入有误,请重新输入!\n") | |
continue | |
player_choice = int(x) | |
total_game += 1 | |
if mode == 'normal': | |
computer_choice = randint(0, 2) | |
elif mode == 'hard': | |
if player_choice == 0: | |
cal = randint(1, 10) | |
if cal <= 2: | |
computer_choice = 2 | |
else: | |
computer_choice = randint(0, 1) | |
elif player_choice == 1: | |
cal = randint(1, 10) | |
if cal <= 2: | |
computer_choice = 0 | |
else: | |
computer_choice = randint(1, 2) | |
else: | |
cal = randint(1, 10) | |
if cal <= 2: | |
computer_choice = 1 | |
else: | |
while True: | |
computer_choice = randint(0, 2) | |
if computer_choice != 1: | |
break | |
elif mode == 'easy': | |
if player_choice == 0: | |
cal = randint(1, 10) | |
if cal <= 7: | |
computer_choice = 2 | |
else: | |
computer_choice = randint(0, 1) | |
elif player_choice == 1: | |
cal = randint(1, 10) | |
if cal <= 7: | |
computer_choice = 0 | |
else: | |
computer_choice = randint(1, 2) | |
else: | |
cal = randint(1, 10) | |
if cal <= 7: | |
computer_choice = 1 | |
else: | |
while True: | |
computer_choice = randint(0, 2) | |
if computer_choice != 1: | |
break | |
choices = ['剪刀', '石头', '布'] | |
print(f"你出的是{choices[player_choice]},电脑出的是{choices[computer_choice]}。") | |
if player_choice == computer_choice: | |
print("本局平局!\n") | |
elif (player_choice == 0 and computer_choice == 2) or (player_choice == 1 and computer_choice == 0) or (player_choice == 2 and computer_choice == 1): | |
player_wins += 1 | |
print("你赢了本局!\n") | |
else: | |
print("电脑赢了本局!\n") | |
if __name__ == "__main__": | |
ques10() |
# 二分法求平方根
二分法求 n 的平方根。
from tkinter import * | |
import tkinter as tk | |
def ques11(): | |
def Bin_recu(target, left, right, precision): | |
mid = (left + right) / 2 | |
if abs(mid**2 - target) < precision: | |
return mid | |
elif mid**2 < target: | |
return Bin_recu(target, mid, right, precision) | |
elif mid**2 > target: | |
return Bin_recu(target, left, mid, precision) | |
else: | |
return None | |
def my_sqrt(n, precision=1e-7): | |
if n >= 1: | |
return Bin_recu(n, 0, n, precision) | |
else: | |
return Bin_recu(n, 0, 1, precision) | |
print(my_sqrt(10)) | |
print(my_sqrt(10, 1e-12)) | |
print(my_sqrt(100)) | |
print(my_sqrt(100, 1e-14)) | |
if __name__ == "__main__": | |
ques11() |
# 文件排序
对给定的文件名列表,根据文件名前的数字部分进行排序,输出排序后的文件名列表。
goal = ['1.py', '11.py', '13.py', '3.py', '5.py', '7.py', '9.py']
def ques12(): | |
goal = ['1.py', '11.py', '13.py', '3.py', '5.py', '7.py', '9.py'] | |
new_goal = sorted(goal, key=lambda x: int(x.split('.')[0])) | |
print(new_goal) | |
if __name__ == "__main__": | |
ques12() |
# 成绩排序
对学生成绩进行排序,首先按姓名的字母顺序排序,然后按总分从高到低排序(总分相同的按姓名字母顺序排序)。
scores = [
['0121801101266','刘雯',92,73,72,64],
['0121801101077','张佳喜',81,97,61,98],
['0121801101249','张红发',88,66,71,85],
['0121813570483','王昊煜',93,73,71,90],
['0121801101092','曹洋',85,62,71,76],
['0121801101271','徐肖剑',83,73,97,96],
['0121801101565','王雅楠',94,82,96,98],
['0121801101864','胡天旭',63,99,78,89],
['0121801101930','苏琪琦',67,61,68,74],
['0121813570392','项子烜',64,72,85,96],
['0121813570159','黄碧君',94,64,92,64],
['0121801101664','李欣',62,63,92,87],
['0121801101825','何乐',67,97,74,70],
['0121801101707','兰贵能',70,89,77,85],
['0121801101950','周淼',91,72,72,86]]
def ques13(): | |
scores = [ | |
['0121801101266','刘雯',92,73,72,64], | |
['0121801101077','张佳喜',81,97,61,98], | |
['0121801101249','张红发',88,66,71,85], | |
['0121813570483','王昊煜',93,73,71,90], | |
['0121801101092','曹洋',85,62,71,76], | |
['0121801101271','徐肖剑',83,73,97,96], | |
['0121801101565','王雅楠',94,82,96,98], | |
['0121801101864','胡天旭',63,99,78,89], | |
['0121801101930','苏琪琦',67,61,68,74], | |
['0121813570392','项子烜',64,72,85,96], | |
['0121813570159','黄碧君',94,64,92,64], | |
['0121801101664','李欣',62,63,92,87], | |
['0121801101825','何乐',67,97,74,70], | |
['0121801101707','兰贵能',70,89,77,85], | |
['0121801101950','周淼',91,72,72,86]] | |
name = sorted(scores, key=lambda x: x[1]) | |
score = sorted(scores, key=lambda x: (sum(x[2:]), x[1]) , reverse=True) | |
print("按姓名排序:") | |
print(name) | |
print("按总分排序,总分一样的按姓名排序:") | |
print(score) | |
if __name__ == "__main__": | |
ques13() |
# 合法日期
设计函数 valid (year, month, day) 验证输入的日期是否合法,考虑闰年和平年 2 月天数不同的情况。设计函数 calc (year, month, day) 计算天数。
def ques14(): | |
def leap(year): | |
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): | |
return True | |
else: | |
return False | |
def valid(year, month, day): | |
if month < 1 or month > 12: | |
return False | |
if day < 1: | |
return False | |
if month in [1, 3, 5, 7, 8, 10, 12]: | |
if day > 31: | |
return False | |
elif month in [4, 6, 9, 11]: | |
if day > 30: | |
return False | |
elif month == 2: | |
if leap(year): | |
if day > 29: | |
return False | |
else: | |
if day > 28: | |
return False | |
return True | |
def calc(year, month, day): | |
days_in_month = [31, 28 + int(leap(year)), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] | |
if valid(year, month, day) == False: | |
print("输入的日期不合法,无法计算天数。") | |
return | |
total_days = sum(days_in_month[:month - 1]) + day | |
print(f"{year}年{month}月{day}日是该年的第{total_days}天。") | |
y = int(input("请输入年份:")) | |
m = int(input("请输入月份:")) | |
d = int(input("请输入日期:")) | |
calc(y, m, d) | |
if __name__ == "__main__": | |
ques14() |
# 文件读写
文件读写,编写一个程序,允许用户输入一段文本,将其写入到一个名为 text.txt 的文件中,然后读取该文件的内容并打印出来。
def ques15(): | |
file = open('text.txt', 'w', encoding='utf-8') | |
content = input("请输入写入文件的内容:") | |
file.write(content) | |
file.close() | |
with open('text.txt', 'r', encoding='utf-8') as file: | |
content = file.read() | |
print("文件内容如下:") | |
print(content) | |
file.close() | |
if __name__ == "__main__": | |
ques15() |
# 照片批量复制与重命名
照片批量复制与重命名,编写一个程序,将指定文件夹中的所有照片文件复制到另一个文件夹中,并按照指定的命名规则进行重命名。命名规则为:efeon_原文件名_序号。扩展名,其中序号从 001 开始递增。支持的照片文件扩展名包括.jpg、.jpeg 和.png。
def ques16(): | |
import os | |
import shutil | |
from pathlib import Path | |
import time | |
SOURCE_DIR = '照片汇总' | |
DEST_DIR = '目标文件夹' | |
PREFIX = 'efeon' | |
ALLOW_EXTS = {'.jpg', '.jpeg', '.png'} | |
def copy_photos_with_os(): | |
print("=" * 50) | |
print("使用os.path方式") | |
print("=" * 50) | |
if not os.path.exists(DEST_DIR): | |
os.makedirs(DEST_DIR, exist_ok=True) | |
print(f"已创建目标文件夹:{DEST_DIR}") | |
source_files = os.listdir(SOURCE_DIR) | |
count = 1 | |
for filename in source_files: | |
ext = os.path.splitext(filename)[1].lower() | |
if ext not in ALLOW_EXTS: | |
continue | |
name_without_ext = os.path.splitext(filename)[0] | |
new_filename = f'{PREFIX}_{name_without_ext}_{count:03d}{ext}' | |
src_path = os.path.join(SOURCE_DIR, filename) | |
dest_path = os.path.join(DEST_DIR, new_filename) | |
shutil.copy2(src_path, dest_path) | |
print(f"已复制文件:{src_path} 到 {dest_path}") | |
count += 1 | |
time.sleep(0.3) | |
print(f"\n共处理{count - 1}张照片") | |
def main(): | |
print("=" * 50) | |
print("照片批量复制与重命名程序") | |
print("=" * 50) | |
if not Path(SOURCE_DIR).exists(): | |
print(f"源文件夹 {SOURCE_DIR} 不存在。") | |
print("请确保源文件夹存在并包含照片后再运行此程序。") | |
return | |
copy_photos_with_os() | |
print("\n" + "=" * 50 + "\n") | |
print("项目处理完成!") | |
print("=" * 50) | |
main() | |
if __name__ == "__main__": | |
ques16() |
# 带有菜单栏的简单 GUI 应用程序
使用 Tkinter 创建一个带有菜单栏的简单 GUI 应用程序,菜单栏包含 “文件” 和 “编辑” 两个菜单,每个菜单下有若干选项(如 “新建”、“保存”、“退出” 等),点击菜单选项时弹出相应的提示信息。
def ques17(): | |
top = Tk() | |
top.title("菜单栏示例") | |
menu = Menu(top) | |
# 禁用默认的可分离虚线菜单 | |
fmenu = Menu(menu, tearoff=0) | |
for item in ['新建', '保存', '另存为', '关闭']: | |
fmenu.add_command(label=item) | |
emenu = Menu(menu, tearoff=0) | |
for item in ['复制', '粘贴', '全选', '清除']: | |
emenu.add_command(label=item) | |
menu.add_cascade(label='文件', menu=fmenu) | |
menu.add_cascade(label='编辑', menu=emenu) | |
top['menu'] = menu | |
top.mainloop() | |
if __name__ == "__main__": | |
ques17() |
# HTML 爬虫
写一个对豆瓣电影 Top250 的爬虫程序,爬取电影名称、评分和排名并打印出来。
def ques18(): | |
import requests | |
from bs4 import BeautifulSoup | |
url = 'https://movie.douban.com/top250' | |
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} | |
try: | |
response = requests.get(url, headers=header) | |
html = response.text | |
soup = BeautifulSoup(html, 'lxml') | |
movies = soup.find_all('div', class_='item') | |
movie_img = [] | |
for i, movie in enumerate(movies): | |
movie_title = movie.find('span', class_='title').text | |
movie_rating = movie.find('span', class_='rating_num').text | |
movie_img.append(movie.find('img')['src']) | |
index = movie.find('em') | |
print(f"电影名称:{movie_title},评分:{movie_rating},排名:{index.text}") | |
except requests.RequestException as e: | |
print(f"请求错误: {e}") | |
if __name__ == "__main__": | |
ques18() |
# 简单通讯录系统
编写一个通讯录系统,实现添加、查询、修改和删除联系人信息的功能。
def ques19(): | |
contacts = [] | |
def welcome(): | |
print("=" * 30) | |
print("|| 欢迎使用我的通讯录管理系统\t||") | |
print("|| 【1】添加联系人信息\t\t\t||") | |
print("|| 【2】查询联系人信息\t\t\t||") | |
print("|| 【3】修改联系人信息\t\t\t||") | |
print("|| 【4】删除联系人信息\t\t\t||") | |
print("|| 【0】退出通讯录管理系统\t\t||") | |
print("=" * 30) | |
user = input("请输入数字选择对应的功能:") | |
return user | |
def add(): | |
name = input("请输入联系人姓名:") | |
phone = input("请输入联系人电话:") | |
address = input("请输入联系人地址:") | |
contact = {'name': name, 'phone': phone, 'address': address} | |
contacts.append(contact) | |
print(f"已成功添加联系人:{name}") | |
def search(): | |
name = input("请输入要查询的联系人姓名:") | |
for contact in contacts: | |
if contact['name'] == name: | |
print(f"联系人信息:姓名:{contact['name']},电话:{contact['phone']},地址:{contact['address']}") | |
return | |
print("未找到该联系人。") | |
def modify(): | |
name = input("请输入要修改的联系人姓名:") | |
for contact in contacts: | |
if contact['name'] == name: | |
new_phone = input("请输入新的联系电话(留空则不修改):") | |
new_address = input("请输入新的联系地址(留空则不修改):") | |
if new_phone: | |
contact['phone'] = new_phone | |
if new_address: | |
contact['address'] = new_address | |
print(f"已成功修改联系人:{name}") | |
return | |
print("未找到该联系人。") | |
def delete(): | |
name = input("请输入要删除的联系人姓名:") | |
for contact in contacts: | |
if contact['name'] == name: | |
contacts.remove(contact) | |
print(f"已成功删除联系人:{name}") | |
return | |
print("未找到该联系人。") | |
while True: | |
choice = welcome() | |
if choice == '1': | |
add() | |
elif choice == '2': | |
search() | |
elif choice == '3': | |
modify() | |
elif choice == '4': | |
delete() | |
elif choice == '0': | |
print("已退出通讯录管理系统,欢迎下次再来!") | |
break | |
else: | |
print("输入有误,请重新输入!") | |
if __name__ == "__main__": | |
ques19() |
# 爬取图片
爬取给定网址的所有图片链接并通过链接下载到本地目录。
def ques20(): | |
import requests | |
import fake_useragent as fua | |
from bs4 import BeautifulSoup | |
url = 'https://yunhdan.github.io' | |
header = {'User-Agent': fua.UserAgent().random} | |
try: | |
img_headers = { | |
"User-Agent": header["User-Agent"], | |
"Referer": url, | |
} | |
response = requests.get(url, headers=header, timeout=10) | |
html = response.text | |
soup = BeautifulSoup(html, 'lxml') | |
img_src_list = [] | |
for img in soup.find_all('img', class_=['image', 'lozaded']): | |
img_src_list.append(img['src']) | |
for img in soup.find_all('img', class_=['lozaded']): | |
img_src_list.append(img['src']) | |
for idx, img_url in enumerate(img_src_list): | |
img_data = requests.get(img_url, headers=img_headers, timeout=10) | |
if img_data.status_code != 200 or "image" not in img_data.headers.get("Content-Type", ""): | |
print(f"跳过第 {idx} 张,返回码 {img_data.status_code},Content-Type {img_data.headers.get('Content-Type')}") | |
continue | |
with open(f'img/img{idx + 1}.jpg', 'wb') as img_file: | |
img_file.write(img_data.content) | |
print(f"已下载图片:img{idx + 1}.jpg") | |
print("图片下载完成!") | |
except requests.RequestException as e: | |
print(f"请求错误: {e}") | |
if __name__ == "__main__": | |
ques20() |
# 打印月历
输入指定的年和月,输出该月的月历。要输出指定年 / 月的月历,要解决以下 2 个问题:
1. 确定该月的第 1 天是星期几,因为这决定了该月月历第 1 天的起始输出位置。
2. 确定该月的天数。某月的天数可以是 31、30、29、28 当中的一种。月份是 31 天还是 30 天容易判断,因为有固定的月份对应。但对于 2 月来说,是 29 天还是 28 天,还需要判断年份是否为闰年。因此该问题衍生出一个判断闰年的子问题。
输出月历。该问题的解决需要依赖上述两个问题。
因此绘制月历的问题可分为 4 个子问题,每个子问题可由一个函数实现。具体如下:
week_num_of_date (year,month,day) # 根据给定的日期,返回是星期几
is_leap_year (year) # 判断指定年份是否为闰年
days_of_month (year,month) # 根据给定的年、月,返回该月的天数
print_month_calendar (year,month) # 输出月历
给定日期,计算并返回是星期几。
函数中 n0 的值位于 06 之间,0 表示星期日,16 表示星期一至星期六。
为符合使用习惯,若 n0 等于 0,则返回 7,即令 7 对应星期日。
def ques21(): | |
def week_num_of_date(year, month, day): # day 为 1,则返回该月第 1 天是星期几 | |
y0 = year - (14 - month) // 12 | |
y1 = y0 + y0 // 4 - y0 // 100 + y0 // 400 | |
m0 = month + 12 * ((14 - month) // 12) - 2 | |
n0 = (day + y1 + (31 * m0) // 12) % 7 | |
if n0 == 0: | |
return 7 | |
else: | |
return n0 | |
# 判断给定年份是否为闰年,是返回 True,否则返回 False。 | |
def is_leap_year(year): | |
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): | |
return True | |
else: | |
return False | |
# 根据给定的年份和月份,返回该月的天数。 | |
def days_of_month(year, month): | |
if month in [1, 3, 5, 7, 8, 10, 12]: | |
return 31 | |
elif month in [4, 6, 9, 11]: | |
return 30 | |
elif month == 2: | |
if is_leap_year(year): | |
return 29 | |
else: | |
return 28 | |
else: | |
return None | |
# 输出月历 | |
def print_month_calendar(year, month): | |
print(f" {year}年{month}月") | |
print("一 二 三 四 五 六 日") | |
first_weekday = week_num_of_date(year, month, 1) # 先获得该月 1 号是星期几 | |
days_in_month = days_of_month(year, month) # 再获得该月的天数 | |
day_counter = 1 # 累计总天数的计数器 | |
for i in range(1, 43): # i 是指针,表示在月历中的位置 | |
if i < first_weekday: | |
print(" ", end="") | |
elif day_counter <= days_in_month: | |
print(f"{day_counter:2d} ", end="") | |
day_counter += 1 | |
else: | |
print(" ", end="") | |
if i % 7 == 0: | |
print() # 到月历一行的末尾换行 | |
year = int(input("请输入年份:")) | |
month = int(input("请输入月份:")) | |
print_month_calendar(year, month) | |
if __name__ == "__main__": | |
ques21() |
# wxpython 相关
一、使用 wxPython 创建一个简单的窗口,窗口中包含一个标签和一个按钮,点击按钮时弹出一个消息框显示提示信息。
二、 使用 wxPython 创建一个美观的 Python 代码编辑器。代码编辑器应包含基本的文本编辑功能,如打开文件、保存文件、剪切、复制、粘贴等。代码编辑器应支持语法高亮显示,至少支持 Python 代码的高亮显示。代码编辑器应具有行号显示功能,方便用户查看代码行数。代码编辑器应支持自动缩进功能,方便用户编写代码。代码编辑器应具有查找和替换功能,方便用户在代码中查找特定内容并进行替换。代码编辑器应支持多标签页功能,允许用户同时打开多个文件进行编辑。代码编辑器应具有良好的用户界面设计,易于使用和操作。
def ques22(): | |
def on_btn(event): | |
wx.MessageBox("你点击了按钮!", "提示", wx.OK | wx.ICON_INFORMATION) | |
app = wx.App() | |
frm = wx.Frame(None, title="简单的wxPython窗口", size=(300, 300), pos=wx.Point(100, 100)) | |
frm.Show() | |
pl = wx.Panel(frm, size=wx.Size(300, 300), pos=wx.Point(100, 100)) | |
pl.Show() | |
staticText = wx.StaticText(pl, label="欢迎使用wxPython!", pos=(130, 130)) | |
staticText.Show() | |
btn = wx.Button(pl, label="点击我", pos=(200, 150)) | |
btn.Show() | |
frm.Bind(wx.EVT_BUTTON, on_btn, btn) | |
app.MainLoop() | |
def ques23(): | |
import wx | |
import wx.stc as stc | |
class CodeEditor(wx.Frame): | |
def __init__(self, parent, title): | |
super(CodeEditor, self).__init__(parent, title=title, size=(800, 600)) | |
self.InitUI() | |
self.Centre() | |
self.Show() | |
def InitUI(self): | |
panel = wx.Panel(self) | |
vbox = wx.BoxSizer(wx.VERTICAL) | |
self.notebook = wx.Notebook(panel) | |
vbox.Add(self.notebook, 1, wx.EXPAND) | |
panel.SetSizer(vbox) | |
menubar = wx.MenuBar() | |
fileMenu = wx.Menu() | |
openItem = fileMenu.Append(wx.ID_OPEN, '打开\tCtrl+O') | |
saveItem = fileMenu.Append(wx.ID_SAVE, '保存\tCtrl+S') | |
fileMenu.AppendSeparator() | |
exitItem = fileMenu.Append(wx.ID_EXIT, '退出\tCtrl+Q') | |
menubar.Append(fileMenu, '&文件') | |
editMenu = wx.Menu() | |
cutItem = editMenu.Append(wx.ID_CUT, '剪切\tCtrl+X') | |
copyItem = editMenu.Append(wx.ID_COPY, '复制\tCtrl+C') | |
pasteItem = editMenu.Append(wx.ID_PASTE, '粘贴\tCtrl+V') | |
menubar.Append(editMenu, '&编辑') | |
self.SetMenuBar(menubar) | |
self.Bind(wx.EVT_MENU, self.OnOpen, openItem) | |
self.Bind(wx.EVT_MENU, self.OnSave, saveItem) | |
self.Bind(wx.EVT_MENU, self.OnExit, exitItem) | |
self.Bind(wx.EVT_MENU, self.OnCut, cutItem) | |
self.Bind(wx.EVT_MENU, self.OnCopy, copyItem) | |
self.Bind(wx.EVT_MENU, self.OnPaste, pasteItem) | |
def OnOpen(self, event): | |
with wx.FileDialog(self, "打开文件", wildcard="Python files (*.py)|*.py|All files (*.*)|*.*", | |
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: | |
if fileDialog.ShowModal() == wx.ID_CANCEL: | |
return | |
pathname = fileDialog.GetPath() | |
try: | |
with open(pathname, 'r', encoding='utf-8') as file: | |
content = file.read() | |
self.AddTab(content, pathname) | |
except IOError: | |
wx.LogError(f"无法打开文件 '{pathname}'。") | |
def OnSave(self, event): | |
current_page = self.notebook.GetCurrentPage() | |
if current_page: | |
with wx.FileDialog(self, "保存文件", wildcard="Python files (*.py)|*.py|All files (*.*)|*.*", | |
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: | |
if fileDialog.ShowModal() == wx.ID_CANCEL: | |
return | |
pathname = fileDialog.GetPath() | |
try: | |
with open(pathname, 'w', encoding='utf-8') as file: | |
content = current_page.GetText() | |
file.write(content) | |
except IOError: | |
wx.LogError(f"无法保存文件 '{pathname}'。") | |
def OnExit(self, event): | |
self.Close() | |
def OnCut(self, event): | |
current_page = self.notebook.GetCurrentPage() | |
if current_page: | |
current_page.Cut() | |
def OnCopy(self, event): | |
current_page = self.notebook.GetCurrentPage() | |
if current_page: | |
current_page.Copy() | |
def OnPaste(self, event): | |
current_page = self.notebook.GetCurrentPage() | |
if current_page: | |
current_page.Paste() | |
def AddTab(self, content, title): | |
stc_ctrl = stc.StyledTextCtrl(self.notebook) | |
stc_ctrl.SetText(content) | |
stc_ctrl.SetLexer(stc.STC_LEX_PYTHON) | |
stc_ctrl.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,back:#FFFFFF") | |
stc_ctrl.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,back:#FFFFFF,italic") | |
stc_ctrl.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,back:#FFFFFF") | |
stc_ctrl.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,back:#FFFFFF") | |
stc_ctrl.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,back:#FFFFFF") | |
stc_ctrl.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold") | |
stc_ctrl.SetMarginType(0, stc.STC_MARGIN_NUMBER) | |
stc_ctrl.SetMarginWidth(0, 40) | |
self.notebook.AddPage(stc_ctrl, title) | |
if __name__ == "__main__": | |
ques22() | |
ques23() |
# HTML 相关
使用 BeautifulSoup 处理 HTML 文本,过滤标题,将所有段落用文本形式打印。
def ques24(): | |
from bs4 import BeautifulSoup | |
html = """ | |
<html> | |
<head><title>示例</title></head> | |
<body> | |
<h1>欢迎</h1> | |
<p>这是第一段。</p> | |
<p>这是第二段。</p> | |
</body> | |
</html> | |
""" | |
soup = BeautifulSoup(html, "lxml") | |
print("标题:", soup.title.get_text()) | |
for p in soup.find_all("p"): | |
print("段落:", p.get_text(strip=True)) | |
if __name__ == "__main__": | |
ques24() |
