if/while/fore根据编号购买商品

根据编号购买商品

输入工资,买一次显示购买清单和余额。

q退出

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:DCC

#定义商品列表
product_list = [
    ("a",1000),
    ("b",2000),
    ("c",3000),
    ("d",4000)
]
shopping_list=[] #初始一个购物车列表
salary =  input("your salary:")
if salary.isdigit(): #isdigit判断是否为整数
    salary = int(salary) #如果是整数,转换格式,便于运算
    while True:
        for item in product_list:
            print(product_list.index(item),item) #输出产品列表
        # for index,item in enumerate(product_list):
        #     print(index,item)
        user_choice = input('>>>>>:')
        if user_choice.isdigit():
            user_choice = int(user_choice) 
            if user_choice < len(product_list) and user_choice >=0: #len(product_list)列表的长度
                p_item = product_list[user_choice]
                if p_item[1] <= salary:
                    shopping_list.append(p_item) #添加至购物车列表
                    salary -= p_item[1] #计算余额
                    print("已经添加了商品%s到你的购物车,账号余额%s" % (shopping_list,salary))
                else:
                    print("余额不足。")
            else:
                print("输入的商品不存在。")

        elif user_choice == 'q':
            print("-------shopping list-------")
            for p in shopping_list:
                print(p)
            print("你的余额:",salary)
            exit()
    else:
        print("invalid option")
原文地址:https://www.cnblogs.com/dcc001/p/5729419.html