首页 > 编程语言 >Python实验课3

Python实验课3

时间:2023-04-25 22:11:10浏览次数:49  
标签:count format Python cart products print id 实验课

实验任务1

    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.可以取到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吗?如果不是,请解释原因

 

实验任务2

task2-1

 

# 列表遍历
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

    # 字典遍历
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

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

实验3

 

 
import string
 
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!'''
 
text_new=text.lower()
letters=string.ascii_lowercase
lst=[0 for i in range(26)]
for i in range(len(text_new)):
    if text_new[i] in letters:
        lst[ord(text_new[i])-97]+=1
con=dict(zip(list(letters),lst))
con_order=sorted(con.items(),key=lambda x:x[1],reverse=True)# 按字典集合中,每一个元组的第二个元素排列。
                                                              # x相当于字典集合中遍历出来的一个元组。
 
for i in range(len(con_order)):
    print(f'{con_order[i][0]}:{con_order[i][1]}')

 

实验4

code_majors={8326:'地信类',
8329:'计算机类',
8330:'气科类',
8336:'防灾工程',
8345:'海洋科学',
8382:'气象工程'}
 
print('{0:-^50}'.format('专业代号信息'))
for i in range(len(code_majors)):
    print(f'{list(code_majors.keys())[i]}: {list(code_majors.values())[i]}')
print('{0:-^50}'.format('学生专业查询'))
while True:
    num=input('请输入学号: ')
    if num=='#':
        break
    else:
        num_sl=int(num[4:8])
        if num_sl in list(code_majors.keys()):
            print(f'专业是: {code_majors[num_sl]}')
        elif num_sl not in list(code_majors.keys()):
            print('不在这些专业中...')

实验5

import random
 
lucky_day=random.randint(1,31)
print(f'猜猜2023年5月哪一天会是你的lucky day{chr(0x1f609)}')
guess=int(input('你有三次机会,猜吧(1~31):'))
flag=0
while lucky_day!=guess:
    if guess>lucky_day:
        print('猜晚了,你的lucky day已经过了')
    elif guess<lucky_day:
        print('猜早了,你的lucky day还没到呢')
    elif guess==lucky_day:
        break
    flag+=1
    if flag==3:
        break
    guess=int(input('再猜(1~31):'))
if flag<3:
    print(f'哇,猜中了{chr(0x1f923)}')
elif flag==3:
    print(f'哇哦,次数用光啦。\n偷偷告诉你,5月你的lucky day是{lucky_day}号。good luck{chr(0x1f60a)}')

 

实验6

datas = {'2049777001': ['篮球', '羽毛球', '美食', '漫画'],
'2049777002': ['音乐', '旅行'],
'2049777003': ['马拉松', '健身', '游戏'],
'2049777004': [],
'2049777005': ['足球', '阅读'],
'2049777006': ['发呆', '闲逛'],
'2049777007': [],
'2049777008': ['书法', '电影'],
'2049777009': ['音乐', '阅读', '电影', '漫画'],
'2049777010': ['数学', '推理', '音乐', '旅行']}
hobby=[]
for i in list(datas.values()):
    hobby+=i
hobby_set=list(set(hobby))
hobby_count=[0 for i in range(len(hobby_set))]
for i in range(len(hobby)):
    hobby_count[hobby_set.index(hobby[i])]+=1
hobby_dict=dict(zip(hobby_set,hobby_count))
hobby_dict_order=sorted(hobby_dict.items(),key=lambda x : x[1],reverse=True)
for i in range(len(hobby_dict_order)):
    print(f'{hobby_dict_order[i][0]}:{hobby_dict_order[i][1]}')

实验7

"""
家用电器销售系统
v1.3
"""
#欢迎信息
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('{:*^48}'.format('*'))
        print('{:10}'.format('编号'), '{:10}'.format('名称'), '{:10}'.format('品牌'), '{:10}'.format('价格'), '{:10}'.format('库存数量'))
        print('{:-^50}'.format('-'))
        for i in range(len(products)):
            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]))
        print('{:-^50}'.format('-'))
    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('{:*^48}'.format('*'))
        print('{:10}'.format('编号'), '{:10}'.format('购买数量'))
        print('{:-^50}'.format('-'))
        for i in range(len(products_cart)):
            print('{:10}'.format(products_cart[i][0]), '{:6}'.format(products_cart[i][1]))
        print('{:-^50}'.format('-'))
    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('谢谢您的光临,下次再见!')

 实验8

task1

'''
家用电器销售系统
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(f'{"":*>48s}')
        print(f'{"编号":10s}{"名称":10s}{"品牌":10s}{"价格":10s}{"库存数量":10s}')
        print(f'{"":->50s}')
        for i in range(len(products)):
            print('{:10}'.format(products[i]['id']),'{:10}'.format(products[i]['name']),'{:10}'.format(products[i]['brand']),'{:10}'.format(products[i]['price']))
        print(f'{"":->50s}')
    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(f'{"":*>48s}')
        print(f'{"编号":10s}{"购买数量":10s}')
        print(f'{"":->50s}')
        for i in range(len(products_cart)):
            print('{:10}'.format(products_cart[i]['id']),'{:6}'.format(products_cart[i]['count']))
        print(f'{"":->50s}')
    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('谢谢您的光临,下次再见!')

 

'''
家用电器销售系统
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(f'{"":*>48s}')
        print(f'{"编号":10s}{"名称":10s}{"品牌":10s}{"价格":10s}{"库存数量":10s}')
        print(f'{"":->50s}')
        for i in range(len(products)):
            print('{:10}'.format(products[i]['id']),'{:10}'.format(products[i]['name']),'{:10}'.format(products[i]['brand']),'{:10}'.format(products[i]['price']))
        print(f'{"":->50s}')
    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(f'{"":*>48s}')
        print(f'{"编号":10s}{"购买数量":10s}')
        print(f'{"":->50s}')
        for i in range(len(products_cart)):
            print('{:10}'.format(products_cart[i]['id']),'{:6}'.format(products_cart[i]['count']))
        print(f'{"":->50s}')
    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('谢谢您的光临,下次再见!')

 

 

 

 

 

标签:count,format,Python,cart,products,print,id,实验课
From: https://www.cnblogs.com/MaYangJie/p/17354102.html

相关文章

  • 人生苦短,我用PYTHON(目录)
    PYTHON基础01-Python基础之简介02-Python基础之虚拟环境03-Python基础之数据类型04-Python基础之格式化输出05-Python基础之深浅复制06-Python基础之散列类型和逻辑运算07-Python基础之流程控制08-Python基础之文件操作09-Python基础之函数10-Pytho......
  • 《Python入门与核心语法》电子书
    《Python入门与核心语法》是由刘永富编写、中国水利水电出版社智博尚书分社编辑整理的电子书,共61页,内容包括Python的下载和安装,代码编写与执行等基础内容。PDF电子书下载: 链接:https://pan.baidu.com/s/1I9HhkKBWuujzk2jBgkR5-w提取码:2022配套视频合集: https://www.bilibili......
  • python字符串集合面试笔试题
    python字符串面试笔试题1:以下代码的输出是?s='foo't='bar'print('barf'in2*(s+t))A.TrueB.Fasle+运算符连接字符串,而*运算符创建多个副本。2*(s+t)的结果是'foobarfoobar',它确实包含字符串'barf'。2:以下代码的输出是?print(ord('foo'))......
  • python实验笔记1
    1.python如何在一行里面输入两个数呢如果直接这样子写会报错n=int(input())m=int(input())要按照下面的写法才可以实现n,m=map(int,input().split())2.python实现排列组合在itertools库中提供了两个函数permutations和combinations可以实现全排列和组......
  • python MAP
    MapMap会将一个函数映射到一个输入列表的所有元素上。这是它的规范:规范map(function_to_apply,list_of_inputs)大多数时候,我们要把列表中所有元素一个个地传递给一个函数,并收集输出。比方说:items=[1,2,3,4,5]squared=[]foriinitems:squared.append(i*......
  • PYTHON FILTER
    Filter顾名思义,filter过滤列表中的元素,并且返回一个由所有符合要求的元素所构成的列表,符合要求即函数映射到该元素时返回值为True.这里是一个简短的例子:number_list=range(-5,5)less_than_zero=filter(lambdax:x<0,number_list)print(list(less_than_zero))#......
  • PYTHON REDUCE
    Reduce当需要对一个列表进行一些计算并返回结果时,Reduce是个非常有用的函数。举个例子,当你需要计算一个整数列表的乘积时。通常在python中你可能会使用基本的for循环来完成这个任务。现在我们来试试reduce:fromfunctoolsimportreduceproduct=reduce((lambdax......
  • PYTHON set
    set(集合)数据结构set(集合)是一个非常有用的数据结构。它与列表(list)的行为类似,区别在于set不能包含重复的值。这在很多情况下非常有用。例如你可能想检查列表中是否包含重复的元素,你有两个选择,第一个需要使用for循环,就像这样:some_list=['a','b','c','b','d','m','......
  • 一行python代码实现并行
    Python在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和GIL,我觉得错误的教学指导才是主要问题。常见的经典Python多线程、多进程教程多显得偏"重"。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。传统的例子简单搜索下"Python多线程教程",不难发现......
  • python 调试 debugger
    调试(Debugging)利用好调试,能大大提高你捕捉代码Bug的。大部分新人忽略了Pythondebugger(pdb)的重要性。在这个章节我只会告诉你一些重要的命令,你可以从官方文档中学习到更多。译者注,参考:https://docs.python.org/2/library/pdb.htmlOrhttps://docs.python.org/3/library/pd......