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

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

时间:2023-04-23 12:22:49浏览次数:34  
标签:语句 count pro 编程 数据类型 cart products print id

实验任务一:

实验源码:

import random
print('用列表存储随机整数: ')
lst = [random.randint(0, 100) for i in range(5)]
print(lst)
print('\n用集合存储随机整数: ')
s1 = {random.randint(0, 100) for i in range(5)}
print(s1)
print('\n用集合存储随机整数: ')
s2 = set()
while len(s2) < 5:
    s2.add(random.randint(0, 100))
print(s2)

  实验截图:

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

0-100 能取到一百

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

0-4 不能取到5    1-4 不包括5

问题3:使用line8代码生成的集合s1,len(s1)一定是5吗?如果不是,请解释原因。 

不一定 有可能生成两个2相同的随机数,而在集合中相同的数只会保留一个

问题4:使用line12-14生成的集合s2,len(s2)一定是5吗?如果不是,请解释原因

实验任务二:

task2_1.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 = [{'书名': '昨日的世界', '作者': '斯蒂芬.茨威格'},
              {'书名': '局外人', '作者': '阿尔贝.加缪'},
              {'书名': '设计中的设计', '作者': '原研哉'},
              {'书名': '万历十五年', '作者': '黄仁宇'},
              {'书名': '刀锋', '作者': '毛姆'}
             ]
for i in range(1,6):
    jh=book_infos[i-1]
    j = jh['书名']
    k = jh['作者']
    print(f'{i}. 《{j}》, {k}')

  实验截图:

试验任务三

实验源码:

text = '''The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''
ls = [chr(i) for i in range(97,123)]
text = text.lower()
word = {}
for i in ls:
    word[i] = text.count(i)
num_list = [(x[1],x[0]) for x in word.items()]
num_lists=sorted(num_list,reverse=True)
for j in num_lists:
    print(f'{j[1]}:{j[0]}')

  

 

 

  实验截图:

 实验任务四

实验源码:

'''8326 地信类
8329 计算机类
8330 气科类
8336 防灾工程
8345 海洋科学
8382 气象工程'''
code_majors = {8326:'地信类',8329:'计算机类',8330:'气科类',8336:'防灾工程',8345:'海洋科学',8382:'气象工程'}
print('{:-^50}'.format('专业代号信息'))
for key,value in code_majors.items():
    print(f'{key}:{value}')
print('{:-^50}'.format('学生专业查询'))
i = 1
while i == 1:
    stu_num = input('请输入学号')
    if  stu_num == '#':
        break
    else:
        zy = int(stu_num[4:8])
        if zy in code_majors:
            print(code_majors[zy])
        else:
            print('不在这些专业中')
print('查询结束...')

  实验截图:

实验任务五

实验源码:

import random
lucky_num = random.randint(1,31)
print('猜猜2023年5月那一天会是你的lucky day'+chr(128521))
i = 1
num = int(input('你有三次机会,猜吧(1~31):'))
if 1<=num < lucky_num:
    print('猜早啦,你的lucky day还没到呢')
elif 31>=num > lucky_num:
    print('猜晚啦,你的lucky day还没到呢')
elif num == lucky_num:
    print('哇,猜中了'+chr(129315))
elif num<1 or num>31:
    print('地球上没有这一天啦,你是外星人吗')
while i < 3:
    if num == lucky_num:
        break
    else:
        num = int(input('再猜(1~31):'))
        if 1<=num < lucky_num:
            print('猜早啦,你的lucky day还没到呢')
            i+=1
        elif 31>=num > lucky_num:
            print('猜晚啦,你的lucky day还没到呢')
            i+=1
        elif num == lucky_num:
            print('哇,猜中了'+chr(129315))
            break
        elif num<1 or num>31:
            print('地球上没有这一天啦,你是外星人吗')
            i+=1

if num != lucky_num:
    print('哇哦,次数用光啦~')
    print(f'偷偷告诉你,5月你的lucky day是{lucky_num}号,good luck'+chr(128522))

  

  实验截图:

 

 实验任务六

实验源码:

datas = {'2049777001': ['篮球', '羽毛球', '美食', '漫画'],
         '2049777002': ['音乐', '旅行'],
         '2049777003': ['马拉松', '健身', '游戏'],
         '2049777004': [],
         '2049777005': ['足球', '阅读'],
         '2049777006': ['发呆', '闲逛'],
         '2049777007': [],
         '2049777008': ['书法', '电影'],
         '2049777009': ['音乐', '阅读', '电影', '漫画'],
         '2049777010': ['数学', '推理', '音乐', '旅行']
        }
ls = []
qw = {}
for value in datas.values():
    ls += value
st = list(set(ls))
for i in st:
    qw[i]=ls.count(i)
num_list = [(x[1],x[0]) for x in qw.items()]
f_num_list = sorted(num_list,reverse=True)
for j in f_num_list:
    print(f'{j[1]}:{j[0]}')

  实验截图:

 实验任务七

task7_1

实验源码

print('欢迎使用家用电器销售系统!')
pro=[['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(pro)):
            print('%-10s'%pro[i][0],'%-10s'%pro[i][1],'%-10s'%pro[i][2],'%10.2f'%pro[i][3],'%10d'%pro[i][4])

        print('-----------------------------------------------------------')
    elif option=='2':
        pro_id=input('请输入您要购买的产品编号:')
        while pro_id not in [item[0]for item in pro]:
            pro_id=input('编号不存在,请重新输入您要购买的产品编号:')
        count=int(input('请输入您要购买的产品数量:'))
        while count > pro[int(pro_id)-1][4]:
            count=input('数量超出库存。请重新输入您要购买的产品数量:')
        if pro_id not in [item[0] for item in products_cart]:
            products_cart.append([pro_id,count])
        else:
            for i in range(len(products_cart)):
                if products_cart[i][0]==pro_id:
                    products_cart[i][1]+=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)):
        pro_index=0
        for j in range(len(pro)):
            if pro[j][0]==products_cart[i][0]:
                pro_index=j
                break
        price=pro[pro_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.9
    elif 20000 < amount :
        amount = amount * 0.85
    else:
        amount=amount*1
    print('购买成功,您需要支付%8.2f元'%amount)
print('谢谢您的光临,下次再见!')

  实验截图

task7_2

实验源码

print('欢迎使用家用电器销售系统!')
pro=[['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('{:<10} {:<10} {:<10} {:<10} {:<10}'.format('编号','名称','品牌','价格','库存数量'))
        print('-----------------------------------------------------------')
        for i in range(len(pro)):
            print('{:<10}'.format(pro[i][0]), '{:<10}'.format(pro[i][1]), '{:<10}'.format(pro[i][2]),
                  '{:<10.2f}'.format(pro[i][3]),
                  '{:>10}'.format(pro[i][4]))

        print('-----------------------------------------------------------')
    elif option=='2':
        pro_id=input('请输入您要购买的产品编号:')
        while pro_id not in [item[0]for item in pro]:
            pro_id=input('编号不存在,请重新输入您要购买的产品编号:')
        count=int(input('请输入您要购买的产品数量:'))
        while count > pro[int(pro_id)-1][4]:
            count=input('数量超出库存。请重新输入您要购买的产品数量:')
        if pro_id not in [item[0] for item in products_cart]:
            products_cart.append([pro_id,count])
        else:
            for i in range(len(products_cart)):
                if products_cart[i][0]==pro_id:
                    products_cart[i][1]+=count
    else:
        print('购物车信息如下:')
        print('************************************')
        print('{:<10} {:<10} '.format('编号','购买数量'))
        print('------------------------------------')
        for i in range(len(products_cart)):
            print('{:10s}'.format(products_cart[i][0]),'{:6d}'.format(products_cart[i][1]))
        print('------------------------------------')
    option=input('操作成功!请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账。')
if len(products_cart)>0:
    amount=0
    for i in range(len(products_cart)):
        pro_index=0
        for j in range(len(pro)):
            if pro[j][0]==products_cart[i][0]:
                pro_index=j
                break
        price=pro[pro_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.9
    elif 20000 < amount :
        amount = amount * 0.85
    else:
        amount=amount*1
    print('购买成功您需要支付{:8.2f}元'.format(amount))
print('谢谢您的光临,下次再见!')

  

实验任务八

task8_1

实验源码

print('欢迎使用家用电器销售系统!')
pro=[{'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':480.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(pro)):
            print('%-10s'%pro[i]['id'],'%-10s'%pro[i]['name'],'%-10s'%pro[i]['brand'],'%10.2f'%pro[i]['price'],'%10d'%pro[i]['count'])
        print('-----------------------------------------------------------')
    elif option == '2':
        pro_id = input('请输入您要购买的产品编号:')
        while pro_id not in [item['id'] for item in pro]:
            pro_id = input('编号不存在,请重新输入您要购买的产品编号:')
        count=int(input('请输入您要购买的产品数量:'))
        while count > pro[int(pro_id)-1]['count']:
            count=input('数量超出库存。请重新输入您要购买的产品数量:')
        if pro_id not in [item['id'] for item in products_cart]:
            products_cart.append({'id':pro_id,'count':count})
        else:
            for i in range(len(products_cart)):
                if products_cart[i].get('id')==pro_id:
                    products_cart[i]['count']+=count

        for i in range(len(pro)) :
            if pro[i]['id']==pro_id:
                pro[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)):
        pro_index=0
        for j in range(len(pro)):
            if pro[j]['id']==products_cart[i]['id']:
                pro_index=j
                break
        price=pro[pro_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.9
    elif 20000 < amount:
        amount = amount * 0.85
    else:
        amount = amount * 1
    print('购买成功,您需要支付%8.2f元' % amount)
print('谢谢您的光临,下次再见!')

  实验截图

task8_2

实验源码

print('欢迎使用家用电器销售系统!')
pro=[{'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':480.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('{:<10} {:<10} {:<10} {:<10} {:<10}'.format('编号','名称','品牌','价格','库存数量'))
        print('-----------------------------------------------------------')
        for i in range(len(pro)):
            print('{:<10}'.format(pro[i]['id']), '{:<10}'.format(pro[i]['name']), '{:<10}'.format(pro[i]['brand']),
                  '{:<10.2f}'.format(pro[i]['price']),
                  '{:>10}'.format(pro[i]['count']))
        print('-----------------------------------------------------------')
    elif option == '2':
        pro_id = input('请输入您要购买的产品编号:')
        while pro_id not in [item['id'] for item in pro]:
            pro_id = input('编号不存在,请重新输入您要购买的产品编号:')
        count=int(input('请输入您要购买的产品数量:'))
        while count > pro[int(pro_id)-1]['count']:
            count=input('数量超出库存。请重新输入您要购买的产品数量:')
        if pro_id not in [item['id'] for item in products_cart]:
            products_cart.append({'id':pro_id,'count':count})
        else:
            for i in range(len(products_cart)):
                if products_cart[i].get('id')==pro_id:
                    products_cart[i]['count']+=count

        for i in range(len(pro)) :
            if pro[i]['id']==pro_id:
                pro[i]['count']-=count
    else:
        print('购物车信息如下:')
        print('************************************')
        print('{:<10} {:<10} '.format('编号','购买数量'))
        print('------------------------------------')
        for i in range(len(products_cart)):
            print('{:10s}'.format(products_cart[i]['id']),'{:6d}'.format(products_cart[i]['count']))
        print('------------------------------------')
    option = input('操作成功!请选择您的操作:1-查看商品;2-购物;3-查看购物车;其他-结账。')
if len(products_cart)>0:
    amount=0
    for i in range(len(products_cart)):
        pro_index=0
        for j in range(len(pro)):
            if pro[j]['id']==products_cart[i]['id']:
                pro_index=j
                break
        price=pro[pro_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.9
    elif 20000 < amount:
        amount = amount * 0.85
    else:
        amount = amount * 1
    print('购买成功您需要支付{:8.2f}元'.format(amount))
print('谢谢您的光临,下次再见!')

  实验截图

 

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

相关文章

  • 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:......
  • 怎么通过查看ddl语句判断数据库的主键是自增的?
    通过查看DDL语句,可以判断数据库表的主键是否是自增的。如果主键使用了AUTO_INCREMENT关键字,则表示主键是自增的。例如,以下是MySQL中创建带有自增主键的表的DDL语句示例:CREATETABLE`users`(`id`int(11)NOTNULLAUTO_INCREMENT,`name`varchar(255)NOTNULL,`email......
  • 如何理解函数编程中的链式调用
    前言在编程中,链式调用是指使用多个函数或方法调用链接在一起来实现某种操作的技术。它可以使代码更简洁、易读,并且能够提高代码的可维护性和可重用性。让我们来深入了解一下链式调用。链式调用的概念链式调用可以理解为将多个函数或方法调用链接在一起,每个函数都返回一个对象,该......
  • Java 编程问题:四、类型推断
    本章包括21个涉及JEP286或Java局部变量类型推断(LVTI)的问题,也称为var类型。这些问题经过精心设计,以揭示最佳实践和使用var时所涉及的常见错误。到本章结束时,您将了解到将var推向生产所需的所有知识。问题使用以下问题来测试您的类型推断编程能力。我强烈建议您在使用解决方案......
  • Java 编程问题:一、字符串、数字和数学
    本章包括39个涉及字符串、数字和数学运算的问题。我们将从研究字符串的一系列经典问题开始,例如计算重复项、反转字符串和删除空格。然后,我们将研究专门用于数字和数学运算的问题,例如两个大数求和和和运算溢出,比较两个无符号数,以及计算除法和模的下限。每个问题都要经过几个解决方......