购物车程序编写方式;
1、首先将其所有的商品列出来,然后在建立一个空列表,用于存放所购买的的商品
2、输入用户的工资,在进行判断输入的是否为数字,如果不是,退出如果是继续执行
3、进入到一个死循环while True:
4、将所有商品列出来,在通过enumerate 在将其下标取出
5、让用户输入所要购买商品的代号数字,并判断用户输入的是否为数字
6、再判断是否为 q 退出,如果为q则打印所购买上的商品,并显示余额,如果不是则通过print提示 输入错误(invaild option),并重新输入
7、如果用户所选择的为数字,在判断数字是否在0和所列出的商品之中通过 len()判断
8、如果在所选商品的范围内,在进行工资的判断,查看是否购买的起,如果可以购买,通过append 添加再将其添加到空列表中去
9、一直循环到用户输入q或者余额不够为止
10、然后通过print将其输出即可
程序如下:
#首先通过列表将产品进行列出 product_list = [ ("iphone",5800), ("moc pro",9800), ("bike",800), ("coffee",31), ("linux book",80) ] shopping_list =[] salary = input("input your salary:") if salary.isdigit(): # 用于判断输入的字符串是否为数字形式 如果为是则为真 salary = int(salary) while True: # for item in product_list: #for item in range product_list: 写法错误 # 方式一: print(product_list.index(item),item) #通过 index 将其下标显示出来用于产品编号 for index,item in enumerate(product_list): # 方法二:index表示下标 item 表示enumerate 中的列表 数据 print(index,item) user_choice = input("please input your want to buy thing:") 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("added %s into shopping cart,your balance 33[31;1m%s 33[0m"%(p_item,salary)) # %s占位符使用时,不能用逗号将其前后分 开,033[31;1m%s033[0m 表示将最后一个占位符所表示的数值进行颜色的设置 else: print("