一个python购物车循环程序:
输入工资》打印列表选择商品》确认购买?(不确认返回商品列表)》计算余额、已购商品计件、累计消费》继续打印商品列表
》确认购买?(q选择退出》退出之后打印已购商品、余额)
# coding=utf-8
# Version:python3.6
# Name:shiwei
# 购物车程序
product_list = [
['phone', '600'],
['computer', '500'],
['camera', '7000'],
['mac', '900'],
] # 产品列表
spend = 0 # 初始累计花费为0
total = 5000 # 今天花的钱不超过这些数
count = 0 # 计件
shopping_list = [] # 定一个列表(购物车),等会用append 函数增加到购物车里面
while True:
salary = input("Iuput your salary:")
if salary.isdigit():
salary = int(salary)
while True:
# for item in product_list:从商品列表里面循环打印
# print(product_list.index(item),item)
for index, item in enumerate(product_list): # enumerate 把列表变成一个类似矩阵的形式,有序号和内容
print('\t',index, item)
choice = input(">>>\t6Choose one commodity you like:")
if choice.isdigit(): # 判断输入的是不是商品
choice = int(choice)
if choice>-1 and choice<len(product_list): # len(product_list) 是列表的长度
product_item = product_list[choice] # 选择商品
product_item[1]=int(product_item[1])# 列表1位置不直接用数字就用这个转换一下
if product_item[1] <= salary:
comfirm = input("You choose \033[032;1m%s\033[0m, are you sure? 'y' means 'sure'"%(product_item[0]))
if comfirm == 'y':
shopping_list.append(product_item) # 运用append 函数把商品加入到购物车程序里面
salary -= product_item[1]
spend += product_item[1] # 累计消费
count += 1
print('You have added \033[032;1m%s\033[0m to your shopping cart, your balance is \033[031;1m%s\033[0m' %(product_item[0], salary))
if spend > total:
print('You spent too much money!')
continue
else:
print('See if there is anything else you like?')
continue # \033[031;1m%s\033[0m 给这个%s加红色
else:
print('\033[042;1mYour money is not enough!\033[0m')
else:
print('Product code is not exist!')
elif choice == 'q':
print("----you’ve bought \033[035;1m%s\033[0m products----"%(count) )
for item_s in shopping_list: # 打印购物车里面的商品
print('>>>', item_s[0])
# for item_s in shopping_list:把购买商品的钱加起来
# spend+=item_s[1]
print(" Cost you \033[033;1m%s\033[0m yuan, Your balance is \033[031;1m%s\033[0m" %(spend, salary))
print('Welcome to visit next time! Good luck!')
#break
exit() # 结束所有循环了, 退出
else:
print('invalid choice!')
else:
print('Error iuput, please input a constant! ')
continue