码迷,mamicode.com
首页 > 编程语言 > 详细

Python 练习1——简易购物车

时间:2017-07-11 19:13:31      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:add   获取   list   and   into   [1]   练习   pen   整数   

简易购物车用于了解购物车的大致原理,利用Python实现简易购物车的基本功能,即:用户将所选择的商品放入购物车中,结算时自动输出所购买商品及所剩余额。

# -*- coding: UTF-8 -*- 
product_list = [
(‘iphone‘,6000),
(‘Mac Pro‘,10000),
(‘bike‘,2000),
(‘Watch‘,16000),
(‘coffee‘,30),
(‘book‘,40)
]
shopping_list = []
salary = input("Input your salary:")
if salary.isdigit(): #isdigit判断是否是一个整数数字,若是则会返回一个真(Ture)
salary = int(salary)
while True:
‘‘‘for item in product_list:
print(product_list.index(item),item) 这样写也是可以的,获取下标作为产品的产品编号
‘‘‘
for index,item in enumerate(product_list):
print(index,item) #打印商品列表
user_choice = input("what choice your buying?")
if user_choice.isdigit(): #选择数字类型
user_choice = int(user_choice)
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)    
salary = salary - p_item[1]
print("Added %s into shopping cart,Your current balance is %s" %(p_item,salary))
else:
print("余额不足")
else:
print("product code [%s] is not exist!" % (user_choice))

elif user_choice == ‘q‘:
print(‘---------shopping list---------
‘)
for p in shopping_list:
print(p)
print("Your current balance:",salary)
exit()
else:
print("invalid option")

简易购物车仅能实现静态的商品列表。

Python 练习1——简易购物车

标签:add   获取   list   and   into   [1]   练习   pen   整数   

原文地址:http://www.cnblogs.com/learnzwb/p/7151725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!