需求:
1.用户输入工资收入
2.打印商品列表
3.用户选择商品,不断的加入购物车
4.检测用户余额,直接捐款,不足提示余额不足
5.允许主动退出,退出时,打印已购商品列表
重点方法:
打印列表下标的方法:
a=['alex','sys','root','admin']
>>> for index,i in enumerate(a):
... print(index,i)
0 alex
1 sys
2 root
3 admin
#!/usr/bin/env python3
# -*-conding:utf-8-**
# __Author__:'liudong'
salary=input("Input your salary:")
if salary.isdigit():
salary=int(salary)
else:
exit("Invalid data type...")
welcom_msg='Welcome to Shopping mall'.center(50,'-')
print(welcom_msg)
exit_flag=False
product_list = [
('Iphone',5000),
('Mac Air',8000),
('Mac Pro',9000),
('XiaoMi',20),
('Coffe',30),
('Bike',800),
('Cloth',200)
]
shop_car = []
while not exit_flag:
#for product_item in product_list:
# p_name,p_price = product_item #可选的写法
print("Products list".center(50,'-'))
# for p_name,p_price in product_list:
# print(p_name,p_price) #由于此方法后面打印下标时,会变成2个无组,所以用下面的方法打印
for item in enumerate(product_list):
index=item[0]
p_name=item[1][0]
p_price=item[1][1]
print(index,'.',p_name,p_price)
user_choice = input('[q=quit,c=check]What do you want to buy?:')
if user_choice.isdigit(): #肯定是选商品
user_choice = int(user_choice)
if user_choice < len(product_list):
p_item = product_list[user_choice]
if p_item[1] <= salary: #买的起
shop_car.append(p_item) #放入购物车
salary -= p_item[1] #扣钱
print('Added [%s] into your shop car,your current balance is \033[31;1m[%s]\033[0m' %
(p_item,salary)) #字体加颜色
else:
print('Your balance is [%s],cannot afford this product..' %salary)
else:
if user_choice == 'q' or user_choice == 'quit':
print('purchased products as blew:'.center(40,'*'))
for item in shop_car:
print(item)
print('END'.center(40,'*'))
print('Your balance is [%s]' %salary)
print('bye.')
exit_flag = True
elif user_choice == 'c' or user_choice == 'check':
print('purchased products as blew:'.center(40, '*'))
for item in shop_car:
print(item)
print('Your balance is \033[41;1m[%s]\033[0m' % salary) #背景加颜色
编程的思维还要加强。。。。。