首页 > 编程语言 >实验3 控制语句与组合数据类型应用编程

实验3 控制语句与组合数据类型应用编程

时间:2023-04-26 11:12:27浏览次数:42  
标签:语句 count 10 编程 数据类型 cart products print id

task1.py
程序代码:
 1 import random
 2 
 3 print('用列表存储随机整数:')
 4 lst = [random.randint(0,100) for i in range(5)]
 5 print(lst)
 6 
 7 print('\n用集合·存储随机整数:')
 8 s1 = {random.randint(0,100) for i in range(5)}
 9 print(s1)
10 
11 print('\n用集合存储随机整数:')
12 s2 = set()
13 while len(s2) < 5:
14     s2.add(random.randint(1,100))
15 print(s2)                                      

运行结果:

 问题1:random.randint(1,100)生成的随机整数范围是?能否取到100?

[1,100],包括1,100.

问题2:利用list(range(5))生成的有序序列范围是?是否包括5?利用list(range(1,5))生成的有序序列范围是?是否包括5?

第一种是[0,4],不包括5,第二种是[1,4]不包括0和5

问题3:使用line8生成的集合s1,len(s1)一定是5吗?

不一定,因为集合不含重复的数值

问题4:line12-14生成的集合s2,len(s2)一定是5吗?

一定是,因为限定了长度。

task2_1.py

程序代码:

 1 # 列表遍历
 2 lst = [55,92,88,79,96]
 3 
 4 # 遍历方式1:使用while + 索引
 5 i = 0
 6 while i < len(lst):
 7     print(lst[i],end = ' ')
 8     i += 1
 9 
10 print()
11 
12 # 遍历方式2:使用for + 索引
13 for i in range(len(lst)):
14     print(lst[i],end = ' ')
15 print()
16 
17 # 遍历方式3: 使用for...in
18 for i in lst:
19     print(i,end = ' ')
20 print()

运行结果:

task2_2.py

运行代码:

 1 # 字典遍历
 2 book_info = {'isbn':'978-7-5356-8297-0',
 3              '书名':'白鲸记',
 4              '作者':'克里斯多夫.夏布特',
 5              '译者':'高文婧',
 6              '出版社':'湖南美术出版社',
 7              '售价':'82'
 8              }
 9 
10 # 遍历key-value对:实现方式1
11 for key,value in book_info.items():
12     print(f'{key}:{value}')
13 print()
14 
15 # 遍历key-value对:实现方式2
16 for item in book_info.items():
17     print(f'{item[0]}:{item[1]}')
18 print()
19 
20 # 遍历值:实现方式1
21 for value in book_info.values():
22     print(value,end = ' ')
23 print()
24 
25 # 遍历值:实现方式2
26 for key in book_info.keys():
27     print(key,end = ' ')
28 print()

运行结果:

 task2_3.py

运行代码:

1 book_infos = [{'书名':'昨日的世界','作者':'斯蒂芬.茨威格'},
2               {'书名':'局外人','作者':'阿尔贝.加缪'},
3               {'书名':'设计中的设计','作者':'原研斋'},
4               {'书名':'万里五十年','作者':'黄仁宇'},
5               {'书名':'万锋','作者':'毛姆'}
6               ]
7 for i in range(len(book_infos)):
8     name = list(book_infos[i].values())
9     print(f'{i + 1}.《{name[0]}》,{name[1]}')

运行结果:

 task3.py

运行代码:

 1 text = '''The Zen of Python, by Tim Peters
 2 
 3           Beautiful is better than ugly.
 4           Explicit is better than implicit.
 5           Simple is better than complex.
 6           Complex is better than complicated.
 7           Flat is better than nested.
 8           Sparse is better than dense.
 9           Readability counts.
10           Special cases aren't special enough to break the rules.
11           Although practicality beats purity.
12           Errors should never pass silently.
13           Unless explicitly silenced.
14           In the face of ambiguity, refuse the temptation to guess.
15           There should be one-- and preferably only one --obvious way to do it.
16           Although that way may not be obvious at first unless you're Dutch.
17           Now is better than never.
18           Although never is often better than *right* now.
19           If the implementation is hard to explain, it's a bad idea.
20           If the implementation is easy to explain, it may be a good idea.
21           Namespaces are one honking great idea -- let's do more of those!
22 
23 
24 x = [text.lower().count(chr(i)) for i in range(97,97 + 26)]
25 d = {}
26 for j in range(26):
27     d.update({chr(j+97):x[j]}
28 y = list(d.items())
29 z = [values,keys for keys,values in y]
30 for values,keys in sorted(z,reverse = True):
31     print(f'{keys}:{values}')

 运行结果:

task4.py

运行代码:

 1 code_majors = {'8326':'地信类',
 2                '8329':'计算机类',
 3                '8330':'气科类',
 4                '8336':'防灾工程',
 5                '8345':'海洋科学',
 6                '8382':'气象工程'}
 7 
 8 print(f'{"专业代号信息":-^50s}')
 9 for keys,values in code_majors.items():
10     print(f'{keys}:{values}')
11 
12 print(f'{"学生专业查询":-^50s}')
13 
14 while True:
15     num = input('请输入学号:')
16     if num != '#':
17         if num[4:8] in code_majors:
18             print(f'专业是:{code_majors.get(num[4:8])}')
19         else:
20             print('不在这些专业中...')
21     if num == '#':
22         print('查询结束...')
23         break

运行结果:

 task5.py

运行代码:

 1 import random
 2 lucky_day = random.randint(1,31)
 3 
 4 print(f'猜猜2023年5月哪一天会是你的lucky_day{chr(0x1f970)}')
 5 
 6 
 7 for i in range(3):
 8     d = eval(input('你有三次机会,猜吧(1,31):'))
 9     if d != lucky_day:
10         i += 1
11         if d < 1 or d > 31:
12             print('地球上没有这一天啦,你是外星人吗')
13         elif d < lucky_day:
14             print('猜早了,你的lucky day还没到呢')
15         elif d > lucky_day:
16             print('猜晚了,你的lucky day已经过了')
17             d = eval(input('再猜(1,31):'))
18         else:
19             d == lucky_day
20             print(f'哇,猜中了{chr(0x1f60d)}')
21             break
22         if i == 3:
23 
24             if d == lucky_day:
25                 print(f'哇,猜中了{chr(0x1f60d)}')
26             else:
27                 print('哇哦,次数用光啦.')
28                 print(f'偷偷告诉你,5月你的lucky day是{lucky_day}号.good luck{chr(0x1f618)}')

运行结果:

 task6.py

运行代码:

 1 datas = {'2049777001': ['篮球', '羽毛球', '美食', '漫画'],
 2          '2049777002': ['音乐', '旅行'],
 3          '2049777003': ['马拉松', '健身', '游戏'],
 4          '2049777004': [],
 5          '2049777005': ['足球', '阅读'],
 6          '2049777006': ['发呆', '闲逛'],
 7          '2049777007': [],
 8          '2049777008': ['书法', '电影'],
 9          '2049777009': ['音乐', '阅读', '电影', '漫画'],
10          '2049777010': ['数学', '推理', '音乐', '旅行']}
11 
12 l = []
13 for values in datas.values():
14     l.extend(values)
15 s = set(l)
16 
17 d = {}
18 for i in s:
19     d[i] = l.count(i)
20 
21 l1 = list(d.items())
22 l2 = [(values,keys) for keys,values in l1]
23 for values,keys in sorted(l2,reverse=True):
24     print(f'{keys}:{values}')

运行结果:

task7.py

运行代码:

 

 1 """
 2 家用电器销售系统
 3 v1.3
 4 """
 5 #欢迎信息
 6 print('欢迎使用家用电器销售系统!')
 7 
 8 #商品数据初始化
 9 products = [
10 ['0001','电视机','海尔',5999.00,20],
11 ['0002','冰箱','西门子',6998.00,15],
12 ['0003','洗衣机','小天鹅',1999.00,10],
13 ['0004','空调','格力',3900.00,10],
14 ['0005','热水器','美的',688.00,30],
15 ['0006','笔记本','联想',5699.00,10],
16 ['0007','微波炉','苏泊尔',480.50,33],
17 ['0008','投影仪','松下',1250.00,12],
18 ['0009','吸尘器','飞利浦',999.00,9]
19 ]
20 
21 #初始化用户购物车
22 products_cart = []
23 
24 option = input('请选择您的操作;1-查看商品;2-购物;3—查看购物车;其他-结账')
25 
26 while option in['1', '2', '3']:
27     if option == '1':
28         # 产品信息列表
29         print('产品和价格信息如下:')
30         print('{:*^48}'.format('*'))
31         print('{:10}'.format('编号'), '{:10}'.format('名称'), '{:10}'.format('品牌'), '{:10}'.format('价格'), '{:10}'.format('库存数量'))
32         print('{:-^50}'.format('-'))
33         for i in range(len(products)):
34             print('{:10}'.format(products[i][0]), '{:10}'.format(products[i][1]), '{:10}'.format(products[i][2]), '{:10}'.format(products[i][3]), '{:10}'.format(products[i][4]))
35         print('{:-^50}'.format('-'))
36     elif option == '2':
37         product_id = input('请输入您要购买的产品编号:')
38         while product_id not in [item[0] for item in products]:
39             product_id = input('编号不存在,请重新输入您要购买的产品编号:')
40 
41         count = int(input('请输入您要购买的产品数量:'))
42         while count > products[int(product_id)-1][4]:
43             count = int(input('数量超出库存,请重新输入您要购买的产品数量:'))
44         # 将所购买的商品加入购物车
45         if product_id not in [item[0] for item in products_cart]:
46             products_cart.append([product_id,count])
47         else:
48             for i in range(len(products_cart)):
49                 if products_cart[i][0] == product_id:
50                     products_cart[i][1]+=count
51         # 更新商品列表
52         for i in range(len(products)):
53             if products[i][0] == product_id:
54                 products[i][4] -= count
55     else:
56         print('购物车信息如下:')
57         print('{:*^48}'.format('*'))
58         print('{:10}'.format('编号'), '{:10}'.format('购买数量'))
59         print('{:-^50}'.format('-'))
60         for i in range(len(products_cart)):
61             print('{:10}'.format(products_cart[i][0]), '{:6}'.format(products_cart[i][1]))
62         print('{:-^50}'.format('-'))
63     option = input('操作成功!请选择你的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')

运行结果:

task8.1.py

运行代码:

 1 '''
 2 家用电器销售系统
 3 v1.4
 4 '''
 5 # 欢迎信息
 6 print('欢迎使用家用电器销售系统!')
 7 # 商品数据初始化
 8 products=[
 9   {'id':'0001','name':'电视机','brand':'海尔','price':5999.00,'count':20},
10   {'id':'0002','name':'冰箱','brand':'西门子','price':6998.00,'count':15},
11   {'id':'0003','name':'洗衣机','brand':'小天鹅','price':1999.00,'count':10},
12   {'id':'0004','name':'空调','brand':'格力','price':3900.00,'count':0},
13   {'id':'0005','name':'热水器','brand':'格力','price':688.00,'count':30},
14   {'id':'0006','name':'笔记本','brand':'联想','price':5699.00,'count':10},
15   {'id':'0007','name':'微波炉','brand':'苏泊尔','price':580.00,'count':33},
16   {'id':'0008','name':'投影仪','brand':'松下','price':1250.00,'count':12},
17   {'id':'0009','name':'吸尘器','brand':'飞利浦','price':999.00,'count':9},
18   ]
19 # 初始化用户购物车
20 products_cart = []
21 option = input('请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
22 while option in ['1', '2', '3']:
23     if option == '1':
24         # 产品信息列表
25         print('产品和价格信息如下:')
26         print(f'{"":*>48s}')
27         print(f'{"编号":10s}{"名称":10s}{"品牌":10s}{"价格":10s}{"库存数量":10s}')
28         print(f'{"":->50s}')
29         for i in range(len(products)):
30             print('{:10}'.format(products[i]['id']),'{:10}'.format(products[i]['name']),'{:10}'.format(products[i]['brand']),'{:10}'.format(products[i]['price']))
31         print(f'{"":->50s}')
32     elif option == '2':
33         product_id = input('请输入您要购买的商品编号:')
34         while product_id not in [item['id'] for item in products]:
35             product_id = input('编号不存在,请重新输入您要购买的产品编号:')
36         count = int(input('请输入您要购买的产品数量:'))
37         while count > products[int(product_id)-1]['count']:
38             count = int(input('数量超出库存,请重新输入您要购买的产品数量:'))
39         # 将所购买的产品加入购物车
40         if product_id not in [item['id'] for item in products_cart]:
41             products_cart.append({'id':product_id,'count':count})
42         else:
43             for i in range(len(products_cart)):
44                 if products_cart[i].get('id') == product_id:
45                     products_cart[i]['count'] += count
46     # 更新商品列表
47         for i in range(len(products)):
48             if products[i]['id'] == product_id:
49                 products[i]['count'] -= count
50     else:
51         print('购物车信息如下')
52         print(f'{"":*>48s}')
53         print(f'{"编号":10s}{"购买数量":10s}')
54         print(f'{"":->50s}')
55         for i in range(len(products_cart)):
56             print('{:10}'.format(products_cart[i]['id']),'{:6}'.format(products_cart[i]['count']))
57         print(f'{"":->50s}')
58     option=input('操作成功!请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
59     # 计算金额
60     if len(products_cart)>0:
61         amount=0
62         for i in range(len(products_cart)):
63             product_index = 0
64             for j in range(len(products)):
65                 if products[j]['id'] == products_cart[i]['id']:
66                     product_index = j
67                     break
68             price = products[product_index]['price']
69             count = products_cart[i]['count']
70             amount += price*count
71             if 5000 < amount <= 10000:
72                 amount = amount*0.95
73             elif 10000 < amount < 20000:
74                 amount = amount*0.90
75             elif amount > 20000:
76                 amount = amount*0.85
77             else:
78                 amount = amount*1
79             print('购买成功,您需要支付%8.2f'%amount)
80         # 退出系统
81         print('谢谢您的光临,下次再见!')

运行结果:

task8.2.py

 1 '''
 2 家用电器销售系统
 3 v1.4
 4 '''
 5 # 欢迎信息
 6 print('欢迎使用家用电器销售系统!')
 7 # 商品数据初始化
 8 products=[
 9   {'id':'0001','name':'电视机','brand':'海尔','price':5999.00,'count':20},
10   {'id':'0002','name':'冰箱','brand':'西门子','price':6998.00,'count':15},
11   {'id':'0003','name':'洗衣机','brand':'小天鹅','price':1999.00,'count':10},
12   {'id':'0004','name':'空调','brand':'格力','price':3900.00,'count':0},
13   {'id':'0005','name':'热水器','brand':'格力','price':688.00,'count':30},
14   {'id':'0006','name':'笔记本','brand':'联想','price':5699.00,'count':10},
15   {'id':'0007','name':'微波炉','brand':'苏泊尔','price':580.00,'count':33},
16   {'id':'0008','name':'投影仪','brand':'松下','price':1250.00,'count':12},
17   {'id':'0009','name':'吸尘器','brand':'飞利浦','price':999.00,'count':9},
18   ]
19 # 初始化用户购物车
20 products_cart = []
21 option = input('请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
22 while option in ['1', '2', '3']:
23     if option == '1':
24         # 产品信息列表
25         print('产品和价格信息如下:')
26         print(f'{"":*>48s}')
27         print(f'{"编号":10s}{"名称":10s}{"品牌":10s}{"价格":10s}{"库存数量":10s}')
28         print(f'{"":->50s}')
29         for i in range(len(products)):
30             print('{:10}'.format(products[i]['id']),'{:10}'.format(products[i]['name']),'{:10}'.format(products[i]['brand']),'{:10}'.format(products[i]['price']))
31         print(f'{"":->50s}')
32     elif option == '2':
33         product_id = input('请输入您要购买的商品编号:')
34         while product_id not in [item['id'] for item in products]:
35             product_id = input('编号不存在,请重新输入您要购买的产品编号:')
36         count = int(input('请输入您要购买的产品数量:'))
37         while count > products[int(product_id)-1]['count']:
38             count = int(input('数量超出库存,请重新输入您要购买的产品数量:'))
39         # 将所购买的产品加入购物车
40         if product_id not in [item['id'] for item in products_cart]:
41             products_cart.append({'id':product_id,'count':count})
42         else:
43             for i in range(len(products_cart)):
44                 if products_cart[i].get('id') == product_id:
45                     products_cart[i]['count'] += count
46     # 更新商品列表
47         for i in range(len(products)):
48             if products[i]['id'] == product_id:
49                 products[i]['count'] -= count
50     else:
51         print('购物车信息如下')
52         print(f'{"":*>48s}')
53         print(f'{"编号":10s}{"购买数量":10s}')
54         print(f'{"":->50s}')
55         for i in range(len(products_cart)):
56             print('{:10}'.format(products_cart[i]['id']),'{:6}'.format(products_cart[i]['count']))
57         print(f'{"":->50s}')
58     option=input('操作成功!请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
59     # 计算金额
60     if len(products_cart)>0:
61         amount=0
62         for i in range(len(products_cart)):
63             product_index = 0
64             for j in range(len(products)):
65                 if products[j]['id'] == products_cart[i]['id']:
66                     product_index = j
67                     break
68             price = products[product_index]['price']
69             count = products_cart[i]['count']
70             amount += price*count
71             if 5000 < amount <= 10000:
72                 amount = amount*0.95
73             elif 10000 < amount < 20000:
74                 amount = amount*0.90
75             elif amount > 20000:
76                 amount = amount*0.85
77             else:
78                 amount = amount*1
79             print('购买成功,您需要支付%8.2f'%amount)
80         # 退出系统
81         print('谢谢您的光临,下次再见!')

运行结果:

 

标签:语句,count,10,编程,数据类型,cart,products,print,id
From: https://www.cnblogs.com/hyy052416/p/17332464.html

相关文章

  • Python的socket编程
    目前处在学习python爬虫的阶段,昨天看到了python的socket模块,分别实现TCP、UDP时间戳回显。1、tcp通信server和client代码#tcpServer.py#!/usr/bin/python#-*-coding:utf-8-*-fromsocketimport*fromtimeimportctimeHOST=''PORT=21156BUFSIZE=1024ADD......
  • Java8 教程_编程入门自学教程_菜鸟教程-免费教程分享
    教程简介Java8(又称为jdk1.8)是Java语言开发的一个主要版本。Java8是oracle公司于2014年3月发布,可以看成是自Java5以来最具革命性的版本。Java8为Java语言、编译器、类库、开发工具与JVM带来了大量新特性。Java8入门教程-从简单的步骤了解Java8,从基本到高级概......
  • MySQL数据类型
     DB哥MySQL高级教程-系统学习MySQL共149课时关注微信公众号免费学:【DB哥】文末有MySQL高级课程目录1、MySQL数据类型MySQL支持多种类型,大致可以分为三类:数值、日期/时间和字符串(字符)类型。 1.2、mysql中编码和字符在mysql中,一个中文汉字所占的字节数与编码格式有......
  • 权限模型与建表及SQL语句编写
    权限模型RBAC权限模型​RBAC权限模型(Role-BasedAccessControl)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。 准备工作      菜单表实体类}  建表及SQL语句编......
  • 实验3 控制语句与组合数据类型应用编程
    任务一importrandomprint('用列表存储随机整数:')lst=[random.randint(0,100)foriinrange(5)]print(lst)print('\n用集合存储随机整数:')s1={random.randint(0,100)foriinrange(5)}print(s1)print('\n用集合存储随机整数:')s2=set()whilele......
  • 编程一小时2023.4.25
    1.#include<bits/stdc++.h>usingnamespacestd;classnumber{intfz,fm;friendnumberoperator+(number&n1,number&n2);public:number(inta=0,intb=1){fz=a;fm=b;}friendintgcd(inta,intb);friendintmin_gb(number&n1......
  • 控制语句与组合数据类型应用
    importrandomprint('用列表存储随机整数:')lst=[random.randint(0,100)foriinrange(5)]print(lst)print('\n用集合存储随机整数:')s1={random.randint(0,100)foriinrange(5)}print(s1)print('\n用集合存储随机整数:')s2=set()whilelen(s2)......
  • 实验3 控制语句与组合数据类型应用编程
    实验任务11importrandom2print('用列表存储随机整数:')3lst=[random.randint(0,100)foriinrange(5)]4print(lst)5print('\n用集合存储随机整数:')6s1={random.randint(0,100)foriinrange(5)}7print(s1)8print('\n用集合存储随机整数:......
  • shell编程总结
    一,执行shell程序文件有三种方法(1)#shfile(2)#.file(3)#sourcefileshell常用的系统变量$#:保存程序命令行参数的数目$?:保存前一个命令的返回码$0:保存程序名$*:以("$1$2...")的形式保存所有输入的命令行参数$@:......
  • 流程控制语句 ——if语句
    一if(关系表达式){语句体;}流程:首先计算关系表达式的值如果关系表达式的值为true就执行语句体如果关系表达式的值为false则执行继续执行后面其他语句 二if(关系表达式){语句体1;}else{语句体2;}流程:计算关系式的值如果关系式的值为true执行语......