python程序2:购物车
主要使用的python的if,while,for循环语句来实现。需要注意循环语句中的结构体。
1、初级版,主要使用循环。
python购物车
#!/usr/bin/env python3
#_*_ encoding:utf8_*_
#__author__:wang
product = [
('oppo',3000),
('hasee',8000),
('bike',800),
('python book',80),
('coffee',20)
]
salary=input("pls input your salary:")
shopping_list = [] #购物车
if salary.isdigit(): #判断输入的是否为整数
salary=int(salary) #强行转换为整数
while True: #死循环
for index,item in enumerate(product): #函数enumerate会自动生成index和item,方便后续增加商品
print(index,item) #打印索引和商品
user_choice=input("select buy>>>>")
if user_choice.isdigit(): #判断输入的值是否为整数
user_choice=int(user_choice)
if user_choice < len(product) and user_choice>=0: #判断是否在范围内
p_item=product[user_choice]
if p_item[1] <= salary: #判断是否金额足够
shopping_list.append(p_item) #加入购买车
salary -= p_item[1]
print("your buy product \033[31:1m %s \033[0m,only \033[31:1m %s \033[0m rmb" %(p_item,salary))
else:
print("your salary only \033[31:1m %s \033[0m rmb,don't buy this prod\033[31:1m %s \033[0m" %(p_item,salary))
else:
print("the prod isn't exist.")
elif user_choice == "q":
print("you buy prod:".center(50,'-'))
for p in shopping_list:
print(p)
print("you only salary\033[32;1m %s \033[0m rmb" %(salary))
exit()
else:
print("input error.")