Python初学时购物车程序练习实例(推荐)

yipeiwu_com5年前Python基础

废话不多说,直接上代码

#Author:Lancy Wu

product_list=[
 ('Iphone',5800),
 ('Mac Pro',9800),
 ('Bike', 800),
 ('Watch', 10600),
 ('Coffee', 31),
 ('Lancy Python', 120)
] #商品列表
shopping_list=[] #定义一个列表来存储已购商品
salary=input("请输入工资:")
if salary.isdigit(): #当输入的内容为数字
 salary=int(salary) #将输入的工资转换成int类型
 while True:
  #循环打印出所有商品列表,有两种写法,一般用下面一种
  # for item in product_list:
  #  print(product_list.index(item),item)
  for index,item in enumerate(product_list): #enumerate()这个方法是取出列表下标
   print(index,item)
  user_choice=input("是否购买商品?如果要购买商品请输入商品编号:")
  if user_choice.isdigit(): #当输入的商品编号为数字
   user_choice=int(user_choice) #将输入的商品编号转换成int类型
   if user_choice<len(product_list) and user_choice>=0: #判断输入的商品编号是否存在
    p_item=product_list[user_choice] #根据商品下标取出所购买的商品
    if p_item[1]<=salary: #当商品的价格小于等于余额
     shopping_list.append(p_item) #将购买的商品存储到shopping_list[]列表中
     salary-=p_item[1]    #计算余额
     print("您购买的商品为%s,余额为\033[31;1m%s\033[0m"%(p_item,salary)) #这个地方做了一下处理,将余额高亮显示
    else: #当商品的价格大于余额
     print("\033[41;1m你的余额只剩[%s]\033[0m"%salary) #这个地方做了一下处理,将余额高亮显示
   else:
     print("该商品不存在!")
  elif user_choice=='q': #当输入的商品编号为q时,打印购买的商品和余额并退出程序
   print("--------以下是购买的商品--------")
   for p in shopping_list:
    print(p)
   print("您的余额为:",salary)
   exit()
  else:
   print("该商品不存在!")

以上这篇Python初学时购物车程序练习实例(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python中使用pngquant压缩png图片的教程

说到png图片压缩,可能很多人知道TinyPNG这个网站。但PS插件要钱(虽然有破解的),Developer API要连到他服务器去,不提网络传输速度,Key也是有每月限制的。 &nbs...

python 中如何获取列表的索引

1.index方法 list_a= [12,213,22,2,32] for a in list_a: print(list_a.index(a)) 结果: 0 1 2 3...

基于python plotly交互式图表大全

基于python plotly交互式图表大全

plotly可以制作交互式图表,直接上代码: import plotly.offline as py from plotly.graph_objs import Scatter, L...

对pandas写入读取h5文件的方法详解

1、引言 通过参考相关博客对hdf5格式简要介绍。 hdf5在存储的是支持压缩,使用的方式是blosc,这个是速度最快的也是pandas默认支持的。 使用压缩可以提磁盘利用率,节省空间。...

python找出一个列表中相同元素的多个索引实例

定义:X=[1,2,3,1,4] 任务:找出元素为1的索引 Solution: # 如果直接用X.index(1),只能得到0这一个索引,而我们需要所有索引. l = len(X)...