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

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

时间:2023-04-23 17:35:02浏览次数:31  
标签:语句 count product 编程 数据类型 cart products print id

task1

源代码

 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(0, 100))
15 print(s2)

 

运行结果

 

问题1: random.randint(0,100) 生成的随机整数范围是?能否取到100? 答:[0, 100]闭区间,可以取到100   问题2:利用 list(range(5)) 生成的有序序列范围是?是否包括5?  答:0~4,不包括5  利用 list(range(1,5)) 生成的有序序列范围是?是否包括5?  答:1~4, 不包括5   问题3:使用line8代码生成的集合s1,len(s1)一定是5吗?如果不是,请解释原因。 答:不一定。若五次循环中出现重复数字,集合只储存一次   问题4:使用line12-14生成的集合s2,len(s2)一定是5吗?如果不是,请解释原因。 答:是的。   task2-1 源代码
 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

源代码

 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(book_info[key], end=' ')

运行结果

task2-3

源代码

book_infos = [{'书名': '昨日的世界', '作者': '斯蒂芬.茨威格'},
              {'书名': '局外人', '作者': '阿尔贝.加缪'},
              {'书名': '设计中的设计', '作者': '原研哉'},
              {'书名': '万历十五年', '作者': '黄仁宇'},
              {'书名': '刀锋', '作者': '毛姆'}
              ]
i = 0
while i < len(book_infos):
    name = book_infos[i]['书名']
    author = book_infos[i]['作者']
    print(f'{i+1}.《{name}》,{author}')
    i += 1

运行结果

 

task3

源代码

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

运行结果

 

task4

源代码

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

运行结果

 

task5

源代码

print('猜猜2023年5月哪一天会是你的lucky day' + u'\U0001F970' )
import random
lucky_day = random.randint(1, 31)
i = 0
while i < 4:
    if i == 0:
        ans = eval(input('你有三次机会,猜吧(1~31):'))
        if ans == lucky_day:
            print('哇哦,猜对啦!')
            break
        elif ans in range(1, lucky_day):
            print('猜早啦,你的lucky day还没到呢' + u'\U0001F49C')
        elif ans in range(lucky_day, 32):
            print('猜晚啦,再试一次' + u'\U0001F49B')
        else:
            print('地球上没有这一天啦,你是外星人吗' + u'\U0001F47D')

    elif i == 3:
        print(f'哇哦,次数用光啦.\n偷偷告诉你,5月你的lucky day是{lucky_day}号。Good luck!')
    else:
        ans = eval(input('再猜(1~31):'))
        if ans == lucky_day:
            print('哇哦,猜对啦!')
            break
        elif ans in range(1, lucky_day):
            print('猜早啦,你的lucky day还没到呢' + u'\U0001F49C')
        elif ans in range(lucky_day, 32):
            print('猜晚啦,再试一次' + u'\U0001F49B')
        else:
            print('地球上没有这一天啦,你是外星人吗' + u'\U0001F47D')
    i = i+1

运行结果

 

task6

源代码
 1 datas = {'2049777001': ['篮球', '羽毛球', '美食', '漫画'],
 2          '2049777002': ['音乐', '旅行'],
 3          '2049777003': ['马拉松', '健身', '游戏'],
 4          '2049777004': [],
 5          '2049777005': ['足球', '阅读'],
 6          '2049777006': ['发呆', '闲逛'],
 7          '2049777007': [],
 8          '2049777008': ['书法', '电影'],
 9          '2049777009': ['音乐', '阅读', '电影', '漫画'],
10          '2049777010': ['数学', '推理', '音乐', '旅行']
11          }
12 hobby = {}
13 for value in list(datas.values()):
14     for i in value:
15         hobby[i] = hobby.get(i, 0) + 1
16 for j in hobby.items():
17     print(f'{j[0]}:{j[1]}')

运行结果

 

task7-1

源代码

# 欢迎信息
print('欢迎使用家用电器销售系统!')
# 商品数据初始化
products = [
    ['0001', '电视机', '海尔', 5999.00, 20],
    ['0002', '冰箱', '西门子', 6998.00, 15],
    ['0003', '洗衣机', '小天鹅', 1999.00, 10],
    ['0004', '空调', '格力', 3900.00, 0],
    ['0005', '热水器', '格力', 688.00, 30],
    ['0006', '笔记本', '联想', 5699.00, 10],
    ['0007', '微波炉', '苏泊尔', 480.00, 33],
    ['0008', '投影仪', '松下', 1250.00, 12],
    ['0009', '吸尘器', '飞利浦', 999.00, 9],
]


# 初始化用户购物车
products_cart = []

option = input('请选择您的操作:1-查看商品;2-购物;3—查看购物车;其他-结账')

while option in['1', '2', '3']:
    if option == '1':
        # 产品信息列表
        print('产品和价格信息如下:')
        print('************************************************')
        print('%-10s' % '编号', '%-10s' % '名称', '%-10s' % '品牌', '%-10s' % '价格', '%-10s' % '库存数量')
        print('-------------------------------------------------')
        for i in range(len(products)):
            print('%-10s' % products[i][0], '%-10s' % products[i][1], '%-10s' % products[i][2], '%10.2f' % products[i][3], '%10d' % products[i][4])
        print('-------------------------------------------------')
    elif option == '2':
        product_id = input('请输入您要购买的产品编号:')
        while product_id not in [item[0] for item in products]:
            product_id = input('编号不存在,请重新输入您要购买的产品编号:')

        count = int(input('请输入您要购买的产品数量:'))
        while count > products[int(product_id)-1][4]:
            count = int(input('数量超出库存,请重新输入您要购买的产品数量:'))
        # 将所购买的商品加入购物车
        if product_id not in [item[0] for item in products_cart]:
            products_cart.append([product_id,count])
        else:
            for i in range(len(products_cart)):
                if products_cart[i][0] == product_id:
                    products_cart[i][1]+=count
        # 更新商品列表
        for i in range(len(products)):
            if products[i][0] == product_id:
                products[i][4] -= count
    else:
        print('购物车信息如下:')
        print('*************************************')
        print('%-10s' % '编号', '%-10s' % '购买数量')
        print('-------------------------------------')
        for i in range(len(products_cart)):
            print('%-10s' % products_cart[i][0], '%6d' % products_cart[i][1])
        print('-------------------------------------')
    option = input('操作成功!请选择你的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
# 计算金额
if len(products_cart) > 0:
    amount = 0
    for i in range(len(products_cart)):
        product_index = 0
        for j in range(len(products)):
            if products[j][0] == products_cart[i][0]:
                product_index = j
                break
        price = products[product_index][3]
        count = products_cart[i][1]
        amount += price*count

    if 5000 < amount <= 10000:
        amount = amount * 0.95
    elif 10000 < amount <= 20000:
        amount = amount * 0.90
    elif amount > 20000:
        amount = amount*0.85
    else:
        amount = amount*1
    print('购买成功,您需要支付%8.2f元' % amount)

# 退出系统
print('谢谢您的光临,下次再见!')

运行结果

task7-2

源代码

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

运行结果

 

task8-1

源代码

'''
家用电器销售系统
v1.4
'''
# 欢迎信息
print('欢迎使用家用电器销售系统!')
# 商品数据初始化
products=[
  {'id':'0001','name':'电视机','brand':'海尔','price':5999.00,'count':20},
  {'id':'0002','name':'冰箱','brand':'西门子','price':6998.00,'count':15},
  {'id':'0003','name':'洗衣机','brand':'小天鹅','price':1999.00,'count':10},
  {'id':'0004','name':'空调','brand':'格力','price':3900.00,'count':0},
  {'id':'0005','name':'热水器','brand':'格力','price':688.00,'count':30},
  {'id':'0006','name':'笔记本','brand':'联想','price':5699.00,'count':10},
  {'id':'0007','name':'微波炉','brand':'苏泊尔','price':580.00,'count':33},
  {'id':'0008','name':'投影仪','brand':'松下','price':1250.00,'count':12},
  {'id':'0009','name':'吸尘器','brand':'飞利浦','price':999.00,'count':9},
  ]
# 初始化用户购物车
products_cart = []
option = input('请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
while option in ['1', '2', '3']:
    if option == '1':
        # 产品信息列表
        print('产品和价格信息如下:')
        print('*********************************************************')
        print('%-10s'%'编号','%-10s'%'名称','%-10s'%'品牌','%-10s'%'价格','%-10s'%'库存数量')
        print('---------------------------------------------------------')
        for i in range(len(products)):
            print('%-10s' %products[i]['id'], '%-10s'%products[i]['name'],'%-10s'%products[i]['brand'],'%-10s'%products[i]['price'],'%-10s'%products[i]['count'])
        print('-----------------------------------------------------')
    elif option == '2':
        product_id = input('请输入您要购买的商品编号:')
        while product_id not in [item['id'] for item in products]:
            product_id = input('编号不存在,请重新输入您要购买的产品编号:')
        count = int(input('请输入您要购买的产品数量:'))
        while count > products[int(product_id)-1]['count']:
            count = int(input('数量超出库存,请重新输入您要购买的产品数量:'))
        # 将所购买的产品加入购物车
        if product_id not in [item['id'] for item in products_cart]:
            products_cart.append({'id':product_id,'count':count})
        else:
            for i in range(len(products_cart)):
                if products_cart[i].get('id') == product_id:
                    products_cart[i]['count'] += count
    # 更新商品列表
        for i in range(len(products)):
            if products[i]['id'] == product_id:
                products[i]['count'] -= count
    else:
        print('购物车信息如下')
        print('*************************')
        print('%-10s'%'编号','%-10s'%'购买数量')
        print('-------------------------')
        for i in range(len(products_cart)):
            print('%-10s'%products_cart[i]['id'],'%6d'%products_cart[i]['count'])
        print('-------------------------')
    option=input('操作成功!请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
    # 计算金额
    if len(products_cart)>0:
        amount=0
        for i in range(len(products_cart)):
            product_index = 0
            for j in range(len(products)):
                if products[j]['id'] == products_cart[i]['id']:
                    product_index = j
                    break
            price = products[product_index]['price']
            count = products_cart[i]['count']
            amount += price*count
            if 5000 < amount <= 10000:
                amount = amount*0.95
            elif 10000 < amount < 20000:
                amount = amount*0.90
            elif amount > 20000:
                amount = amount*0.85
            else:
                amount = amount*1
            print('购买成功,您需要支付%8.2f'%amount)
        # 退出系统
        print('谢谢您的光临,下次再见!')

运行结果

 

task8-2

源代码

'''
家用电器销售系统
v1.4
'''
# 欢迎信息
print('欢迎使用家用电器销售系统!')
# 商品数据初始化
products=[
  {'id':'0001','name':'电视机','brand':'海尔','price':5999.00,'count':20},
  {'id':'0002','name':'冰箱','brand':'西门子','price':6998.00,'count':15},
  {'id':'0003','name':'洗衣机','brand':'小天鹅','price':1999.00,'count':10},
  {'id':'0004','name':'空调','brand':'格力','price':3900.00,'count':0},
  {'id':'0005','name':'热水器','brand':'格力','price':688.00,'count':30},
  {'id':'0006','name':'笔记本','brand':'联想','price':5699.00,'count':10},
  {'id':'0007','name':'微波炉','brand':'苏泊尔','price':580.00,'count':33},
  {'id':'0008','name':'投影仪','brand':'松下','price':1250.00,'count':12},
  {'id':'0009','name':'吸尘器','brand':'飞利浦','price':999.00,'count':9},
  ]
# 初始化用户购物车
products_cart = []
option = input('请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
while option in ['1', '2', '3']:
    if option == '1':
        # 产品信息列表
        print('产品和价格信息如下:')
        print('*********************************************************')
        print(f'{"编号":10}{"名称":10}{"品牌":10}{"价格":10}{"库存数量":10}')
        print('---------------------------------------------------------')
        for i in range(len(products)):
            print('{0[id]:10}{0[name]:10}{0[brand]:10}{0[price]:10}{0[count]:10}'.format(products[i]))
        print('-----------------------------------------------------')
    elif option == '2':
        product_id = input('请输入您要购买的商品编号:')
        while product_id not in [item['id'] for item in products]:
            product_id = input('编号不存在,请重新输入您要购买的产品编号:')
        count = int(input('请输入您要购买的产品数量:'))
        while count > products[int(product_id)-1]['count']:
            count = int(input('数量超出库存,请重新输入您要购买的产品数量:'))
        # 将所购买的产品加入购物车
        if product_id not in [item['id'] for item in products_cart]:
            products_cart.append({'id': product_id, 'count': count})
        else:
            for i in range(len(products_cart)):
                if products_cart[i].get('id') == product_id:
                    products_cart[i]['count'] += count
    # 更新商品列表
        for i in range(len(products)):
            if products[i]['id'] == product_id:
                products[i]['count'] -= count
    else:
        print('购物车信息如下')
        print('*************************')
        print('{:10}{:10}'.format('编号', '购买数量'))
        print('-------------------------')
        for i in range(len(products_cart)):
            print('{0[id]:10}{0[count]:6d}'.format(products_cart[i]))
        print('-------------------------')
    option = input('操作成功!请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账')
    # 计算金额
    if len(products_cart) > 0:
        amount = 0
        for i in range(len(products_cart)):
            product_index = 0
            for j in range(len(products)):
                if products[j]['id'] == products_cart[i]['id']:
                    product_index = j
                    break
            price = products[product_index]['price']
            count = products_cart[i]['count']
            amount += price*count
            if 5000 < amount <= 10000:
                amount = amount*0.95
            elif 10000 < amount < 20000:
                amount = amount*0.90
            elif amount > 20000:
                amount = amount*0.85
            else:
                amount = amount*1
            print('购买成功,您需要支付{:8.2f}元' .format(amount))
        # 退出系统
        print('谢谢您的光临,下次再见!')

运行结果

 

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

相关文章

  • python + informix+基本语句
    importjaydebeapiimportosimportloggingimporttimeclassPostgre_Person:def__init__(self):#打开数据库连接foriinrange(10):try:url=###user=###password=##......
  • Mysql查询语句进阶知识集锦
    前言上次咱们简单的学习了一下select的用法,一篇文章教会你进行Mysql数据库和数据表的基本操作,对数据库大概有了一些基本的了解。咱们接着上次继续来看叭!查询数据如下or查询我们在上学时,会听到这样的话,某某某,你把谁谁谁或者谁谁谁叫过来。这样子的话,我们我们要查询的,就是一个或......
  • 《Linux基础》09. Shell 编程
    目录1:Shell简介2:Shell脚本2.1:规则与语法2.2:执行方式2.3:第一个Shell脚本3:变量3.1:系统变量3.2:用户自定义变量3.2.1:规则3.2.2:基本语法3.2.3:示例3.3:自定义环境变量4:位置参数变量4.1:语法4.2:示例5:预定义变量5.1:语法5.2:示例6:读取标准输入7:运算符8:条件判断8.1:基本判断8.2:文件权限判断8......
  • 实验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()......
  • RBAC权限模型、建表及SQL语句编写
    RBAC权限模型RBAC权限模型(Role-BasedAccessControl)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。建表及SQL语句编写准备工作创建数据库SQL表CREATEDATABASE/*!32312IFNOTEXISTS*/`sg_security`/*!40100DEFAULTCHARACTERSETutf8......
  • 为什么单片机编程放不下超过32万的整数?
    因为你的单片机可能是16位的,c语言16位编译器的int类型占2字节,也就是范围:-2^15~2^15-1 (-32768~32767)。32位的编译器int类型占4字节。这种情况下可以使用longint(16位编译器4字节),也可以使用循环处理整数。 ......
  • 两天学会flask(六)---模板-if语句(3)(20分钟)
    flask模板---if语句jinja2在模板里支持if条件语句,这意味着你可以更加灵活的控制页面的显示,同正常python代码一样,它支持elif和else。对上一篇的实例做一些简单的修改,新建一个if.html文件,内容为:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>......
  • MySQL数据类型之字符型
    字符类型类型说明N的含义是否有字符集最大长度char(n)定长字符字符是255varchar(n)变长字符字符是65535binary(n)定长二进制字节字节否255varbinary(n)变长二进制字节字节否65535tinyblob二进制大对象字节否255blob(n)二进制大对象字节否65535mediumblob(n)二进制大对象字节否16Mlo......
  • MySQL数据类型之日期型
    日期类型日期类型占用空间(字节数)表示范围date41000-01-01~9999-12-31datetime81000-01-0100:00:00.000000~9999-12-3123:59:59.999999timestamp41970-01-0100:00:00.000000UTC~2038-01-1903:14:07.000000UTCyear11901-2155time3-838:59:59.000000~838:59:59.000000date......
  • 一些markdown语句
    网上摘抄的一些Mermaid代码高亮importfunctoolsdefErrorCatch(func):"""Printtheerrorofthedecoratedfunction"""@functools.wraps(func)#等价于func=wrapper_timer(func)defwrapper_timer(*args,**kwargs):try:......