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

yipeiwu_com6年前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 读取excel文件生成sql文件实例详解

python 读取excel文件生成sql文件实例详解 学了python这么久,总算是在工作中用到一次。这次是为了从excel文件中读取数据然后写入到数据库中。这个逻辑用java来写的话...

python使用pygame框架实现推箱子游戏

python使用pygame框架实现推箱子游戏

本代码来源于 《Python和Pygame游戏开发指南》中的 Star Pusher 游戏,供大家参考,具体内容如下 # Star Pusher (a Sokoban clone)...

利用Python的Twisted框架实现webshell密码扫描器的教程

好久以来都一直想学习windows中得iocp技术,即异步通信,但是经过长时间研究别人的c++版本,发现过于深奥了,有点吃力,不过幸好python中的twisted技术的存在方便了我。...

python基础练习之几个简单的游戏

文档介绍 利用python写“猜数字”,“猜词语”,“谁是卧底”这三个游戏,从而快速掌握python编程的入门知识,包括python语法/列表/元组/字典/流程控制/库函数等等。 环境参...

python的set处理二维数组转一维数组的方法示例

for splitValue in set(dataset[:, featureIndex].tolist()): 首先set是一个无序,无重复的数据结构,所以很多时候使用它来进行去重;...