1.本次学习的是购物车的实例练习,具体要求如下:
启动程序后,让用户输入工资,然后打印商品列表;允许用户根据商品编号购买商品;用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒;可随时退出,退出时打印已经购买的商品和余额。
要实现如上要求:a.保存产品、价格的列表;
b.购物车的列表
c.输入工资,打印商品编号和列表
输入数字,判断是否是数字
判断钱够不够,获取商品的价格
如果输入的不是数字,判断是不是q,如果是q,打印购买列表和余额,退出程序。
输入既不是数字,也不是q,不执行循环。
详细代码见如下:
product_list= [
('iphone', 5800),
('mac pro', 9800),
('bike', 800),
('watch', 10600),
('coffe', 31),
('python', 120),
] #定义一个有产品与价格的列表
shopping_list=[] #购物列表为空
salary=input("input your salary:")
if salary.isdigit(): #判断输入的字符串是不是数字,如果是数字,转化为int
salary=int(salary)
while True:
for index,item in enumerate(product_list): #enumerate打印下标
#for item in product_list: #这种方法也可以打印下表,输出语句为print(product_list.index(item),item)
print(index,item)
#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]<=salary: #可以买
shopping_list.append(p_item)
salary-=p_item[1]
print("add %s into shopping cart,current balance is \033[31;1m%s\033[0m"%(p_item,salary)) # \033[31;1m%s\033[0m给%s增加颜色,即给salary增加颜色;而41为整句话添加颜色
else:
print("\033[41;1m余额只剩[%s]啦,不买\033[0m" % salary)
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")
2.在以上代码中用到了enumerate,表示打印下标,在原代码应用如下:
for index,item in enumerate(product_list): #enumerate打印下标
print(index,item)
在命令行中对该字符的功能加以说明,如以下代码;在以下代码中,可以看出,enumerate是将列表中值所对应的下标打印出来。
>>> a=[1,2,3]
>>> for i in enumerate(a):print(i)
...
(0, 1)
(1, 2)
(2, 3)
3.增加一个元组的方法,元组形式如下:names=("alex","jack"),元组只有两种方法,count和index。
names=("alex","jack")