python-购物车实例
程序练习
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
# Author:Jamie Yang
Product_list = [
("Iphone", 5800),
("Mac", 12000),
("Bike", 800),
("Watch", 10600),
("Coffee", 48),
("Book", 45),
]
shopping_list = []
salay = input("Input
your salay:")
if salay.isdigit(): #判断salay输入的字符串是否是只包含数字
salay = int(salay)
while True:
forindex,item in enumerate(Product_list):
print(index,
item)
#for item in Product_list:
#print(Product_list.index(item),item)
user_choice = input("您购买的商品>>>:")
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]
<= salay:
shopping_list.append(p_item)
salay -= p_item[1]
print("Added
%s into shopping cart, your current balance is \033[31;1m%s\033[0m" %(p_item,
salay))
else:
print("\033[41;1m你的余额只剩[%s]啦,买不起你选中的商品\033[0m" %salay)
else:
print("您选中的商品不存在")
elifuser_choice == "q":
print("---------------shopping
list----------")
for p in shopping_list:
print(p)
print("Your current balance:", salay)
exit()
else:
print("invalid option")
exit()
# print("exit......!")
扩展:
isdigit(): #判断salay输入的字符串是否是只包含数字

浙公网安备 33010602011771号