1.编写程序,创建文件data.txt,共100行,第n行存放[100*(n-1), 100*n)之间的素数。
#判断一个数是否为素数
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def write_primes_to_file(filename):
#创建并写入data.txt文件
with open(filename, 'w') as file:
for n in range(1, 101): #从1到100,对应文件中的1到100行
start = 100 * (n - 1)
end = 100 * n
primes = [str(x) for x in range(start, end) if is_prime(x)] #找到当前区间内的所有素数并转换为字符串
file.write(' '.join(primes) + '\n') #将素数写入文件
#调用函数,创建并写入素数到data.txt
write_primes_to_file('data.txt')
![](https://img-blog.csdnimg.cn/direct/7c8deb17c8ee42ca826023db45c7fb4e.png)
2.批量生成50个人的随机信息,包括姓名,性别、年龄和成绩等。
( 提示:c=chr(random.randint(65, 90))可以生成随机大写英文)
1)把生成的信息写入csv文件info.csv。
2)读取info.csv文件,将每一个不及格(成绩小于60)的同学信息存放在以该同学姓名命名的文件中, 这些文件使用dat作为扩展名。
import random
import string
import csv
def generate_random_info(num_students=50):
"""生成随机学生信息"""
info_list = []
for _ in range(num_students):
# 姓名:随机选取2个大写字母
name = ''.join(random.choices(string.ascii_uppercase, k=2))
# 性别:随机选择'M'或'F'
gender = random.choice(['M', 'F'])
# 年龄:18至30岁之间
age = random.randint(18, 30)
# 成绩:0至100之间
score = random.randint(0, 100)
info_list.append([name, gender, age, score])
return info_list
def write_to_csv(info_list, filename='info.csv'):
"""将信息写入CSV文件"""
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['姓名', '性别', '年龄', '成绩']) # 写入表头
writer.writerows(info_list) # 写入数据行
#生成随机信息并写入CSV
random_info = generate_random_info()
write_to_csv(random_info)
def read_and_filter_csv(filename='info.csv'):
"""读取CSV文件并处理不及格学生信息"""
with open(filename, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
next(reader) # 跳过表头
for row in reader:
name, _, _, score = row
if int(score) < 60:
# 创建以学生姓名命名的.dat文件,并写入信息
with open(f'{name}.dat', 'w') as fail_file:
fail_file.write(','.join(row))
#读取CSV并处理不及格学生信息
read_and_filter_csv()
![](https://img-blog.csdnimg.cn/direct/90f30133bb594938bd5e359027ee0463.png)
3.编写程序,显示当前程序的工作路径,并展示"C:\Windows\System32"下所有的空文件夹。
import os
import shutil
def display_current_path():
"""显示当前工作目录路径"""
print("当前工作路径:", os.getcwd())
def find_empty_folders(directory):
"""查找并打印指定路径下的所有空文件夹"""
for root, dirs, files in os.walk(directory):
for folder in dirs:
folder_path = os.path.join(root, folder)
if not os.listdir(folder_path): # 如果文件夹为空
print("空文件夹:", folder_path)
def main():
display_current_path()
# 指定路径,请根据实际情况调整
target_directory = "C:\\Windows\\System32"
try:
find_empty_folders(target_directory)
except PermissionError:
print("没有足够的权限访问目标路径。请尝试以管理员身份运行。")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
main()
![](https://img-blog.csdnimg.cn/direct/35a45d82ecdf4e478fbfb386d7d74da6.png)
4.定义一个异常类,继承Exception类, 捕获下面的过程:
class ScoreOutOfRangeException(Exception):
"""自定义异常类,用于处理成绩输入超出范围的情况"""
def __init__(self, score):
self.score = score
super().__init__(f"{score}: 当前成绩无效")
def get_student_info():
name = input("请输入姓名:")
try:
score_str = input("请输入Python实验成绩(0-100之间):")
score = float(score_str)
if not 0 <= score <= 100:
raise ScoreOutOfRangeException(score)
else:
print(f"{name} 的Python实验成绩为:{score}")
except ValueError:
print("输入错误,请确保成绩是一个数字。")
except ScoreOutOfRangeException as e:
print(e)
# 调用函数
get_student_info()
![](https://img-blog.csdnimg.cn/direct/069ef812c6ba44cfbd3a0836bb7c4cef.png)
![](https://img-blog.csdnimg.cn/direct/0ca345d6da144a7a9536118c757961d7.png)
5.编写程序,要求从键盘输入三个数字(整形或者浮点型),判断这三个数字是否能构成一个三角形。如果可以构成一个三角形,则计算三角形的周长。
1)自定义异常类IllegalArgumentException,对应异常信息为:“a,b,c不能构成三角形”
2)自定义异常类IllegalArgLenException,对应异常信息为:“参数个数不正确”
3)确保键盘输入的是三个值,如果输入值不为3,则抛出IllegalArgLenException异常。
4)确保输入是数字类型,否则抛出类型错误异常。
5)如果输入的三个数不能构成三角形则抛出IllegalArgumentException异常.如果可以构成则显示三角形三个边长,并计算并打印它的周长。
6)不管是否发生异常,程序都会在处理完毕后显示"程序运行结束"。
class IllegalArgumentException(Exception):
"""自定义异常类,表示输入的三个数不能构成三角形"""
pass
class IllegalArgLenException(Exception):
"""自定义异常类,表示输入的参数个数不正确"""
pass
def can_form_triangle(a, b, c):
"""判断三个边长是否能构成三角形"""
return a + b > c and a + c > b and b + c > a
def main():
try:
# 确保输入三个值
sides = input("请输入三个数字,用空格分隔:").split()
if len(sides) != 3:
raise IllegalArgLenException()
# 确保所有输入都是数字
sides = [float(side) for side in sides]
# 判断是否能构成三角形
if can_form_triangle(*sides):
perimeter = sum(sides)
print(f"三角形的边长为:{sides}")
print(f"周长为:{perimeter}")
else:
raise IllegalArgumentException()
except ValueError:
print("输入错误,请确保所有输入均为数字。")
except IllegalArgLenException:
print("参数个数不正确,需要输入三个值。")
except IllegalArgumentException:
print("输入的三个数不能构成三角形。")
finally:
print("程序运行结束")
if __name__ == "__main__":
main()
![](https://img-blog.csdnimg.cn/direct/9ded598abe9448549af5794f40d2c400.png)
![](https://img-blog.csdnimg.cn/direct/50a277e64df949438e3b153ab7571204.png)
![](https://img-blog.csdnimg.cn/direct/509efb5cd2884ee6813c3b7b4c9f7312.png)
6. 假设成年人的体重和身高存在此种关系:
身高(厘米)-100=标准体重(千克)。
如果一个人的体重与其标准体重的差值在正负5之间,显示“体重在正常范围”,其他则显示“体重超标或体重不达标”。
录入你的身高体重,判断是否在合理范围内。要求使用assert断言处理体重不合理(小于-5或者大于5)的情况,请编写程序。
def check_weight(height_cm, weight_kg):
"""
判断体重是否在正常范围内。
:param height_cm: 身高(单位:厘米)
:param weight_kg: 体重(单位:千克)
"""
# 计算标准体重
standard_weight = height_cm - 100
# 计算体重与标准体重的差值
weight_difference = weight_kg - standard_weight
# 使用assert断言处理不合理体重情况
assert -5 <= weight_difference <= 5, "体重超标或体重不达标"
print("体重在正常范围")
# 示例:录入身高和体重
height_input = 175 # 假设身高为175厘米
weight_input = 70 # 假设体重为70千克
try:
check_weight(height_input, weight_input)
except AssertionError as e:
print(e)
![](https://img-blog.csdnimg.cn/direct/a8cc3f430c1144428f5deb1a2a4f0a81.png)
![](https://img-blog.csdnimg.cn/direct/b7cdf87d0c6047c9b758e734b9fcac69.png)