python 购物车程序的编写
1. 描述
购物车程序是用于编写购物网站的基础代码。本文主要用于练习用python进行程序的编写。代码中会用到python中的各种基础函数,条件语句,循环语句,能够给初学者有一个较为清晰的思路。
2. 用到的python内置函数
enumerate() 函数,具体使用方法见:enumerate使用方法
如果想要修改采用print()命令打印出的内容的颜色,可以采用如下的命令:
print("\033[32;1m亲,你钱只剩[%s]了,去买其他产品吧\033[0m"%salary)
其中 \033[32;1m你需要打印出的内容\033[0m
3. 效果
Process finished with exit code 0
4. 代码
product_list = [
("Iphone",5000),
("Apple Watch",3000),
("Macbook Pro",12000),
("Airpods",1500),
("Apple Pencil",680),
("Ipad mini",3200),
("Beats",1800),
]
shopping_list = []
salary = input("请输入你的工资:")
if salary.isdigit():
salary = int(salary)
while True:
for index, item in enumerate(product_list):
print(index,item)
user_choice = input("\033[32;1m你想要买嘛?>>>:\033[0m")
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: #买得起
salary -= p_item[1]
shopping_list.append(p_item)
print("Added %s into you shopping cart,and your current balance is %s"%(p_item,salary))
else:
print("\033[32;1m亲,你钱只剩[%s]了,去买其他产品吧\033[0m"%salary)
else:
print("The product doesn't exist"%user_choice)
elif user_choice == 'q':
print("----------shopping_list------------")
for p in shopping_list:
print(p)
print("Your current balance is:%s"%salary)
exit()
else:
print("Invalid product")