task1.py
1 import random 2 print('用列表存储随机整数: ') 3 lst = [random.randint(0, 100) for i in range(5)] 4 print(lst) 5 print('\n用集合存储随机整数: ') 6 s1 = {random.randint(0, 100) for i in range(5)} 7 print(s1) 8 print('\n用集合存储随机整数: ') 9 s2 = set() 10 while len(s2) < 5: 11 s2.add(random.randint(0, 100)) 12 print(s2)
运行结果:
task2.py
# 列表遍历 lst = [55, 92, 88, 79, 96] # 遍历方式1: 使用while + 索引 i = 0 while i < len(lst): print(lst[i], end = ' ') i += 1 print() # 遍历方式2:使用for + 索引 for i in range(len(lst)): print(lst[i], end = ' ') print() # 遍历方式3: 使用for...in for i in lst: print(i , end = ' ') print()
运行结果:
task2-2.py
# 字典遍历 book_info = {'isbn': '978-7-5356-8297-0', '书名': '白鲸记', '作者': '克里斯多夫.夏布特', '译者': '高文婧', '出版社': '湖南美术出版社', '售价': 82 } # 遍历key-value对:实现方式1 for key, value in book_info.items(): print(f'{key}: {value}') print() # 遍历key-value对:实现方式2 for item in book_info.items(): print(f'{item[0]}: {item[1]}') print() # 遍历值:实现方式1 for value in book_info.values(): print(value, end = ' ') print() # 遍历值: 实现方式2 for key in book_info.keys(): print(book_info[key], end = ' ')
运行结果:
task2_3.py
book_infos = [{'书名': '昨日的世界', '作者': '斯蒂芬.茨威格'}, {'书名': '局外人', '作者': '阿尔贝.加缪'}, {'书名': '设计中的设计', '作者': '原研哉'}, {'书名': '万历十五年', '作者': '黄仁宇'}, {'书名': '刀锋', '作者': '毛姆'} ] n=1 for i in book_infos: print(n,'.''《'+i['书名']+'》',i['作者']) n=n+1
运行结果:
实验任务4
task4.py
title='专业学号信息' print(title.center(50,'-')) code_majors={8326:'地信类',8329:'计算机类',8330:'气科类',8336:'防灾工程',8345:'海洋科学',8382:'气象工程'} for key,value in code_majors.items(): print(f'{key}:{value}') while True: id = input('请输入学号:') if id=='#': print('查询结束...') break major = int(id[4:8]) if major in code_majors.keys(): print(f'专业是:{code_majors[major]}') else: print('不在这些专业中...')
运行结果:
实验任务5
task5.py
import random xO = random.randint(1,31) print('猜猜2023年5月哪一天是你的lucky day 标签:语句,count,product,编程,数据类型,cart,products,print,id From: https://www.cnblogs.com/scy2003/p/17332745.html