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设计】。

相关文章

Pycharm 设置默认头的图文教程

Pycharm 设置默认头的图文教程

1. 设置的路径是File->settings->Editor->File and Code Templates->Python Script内容见图: 这样新...

Python的高级Git库 Gittle

Gittle是一个高级纯python git 库。构建在dulwich之上,提供了大部分的低层机制。 Install it pip install gittle Examples : C...

python解析中国天气网的天气数据

使用方法:terminal中输入复制代码 代码如下:python weather.py http://www.weather.com.cn/weather/101010100.shtml...

Python制作刷网页流量工具

准备 必须环境: Python3 开始 先实现一个简单的版本,直接上代码: import urllib.request import urllib.error #创建get方法...

python 变量初始化空列表的例子

python 不能写new_loss=old_loss=[] 这样 两个变量实际上是同一个list 要分开写new_loss=[] Old_loss=[] 以下列数据文件为例: de...