list列表的使用——购物车程序

需求描述:

购物车程序
1.    启动程序后,让用户输入余额,然后打印商品列表
2.    允许用户根据商品编号购买商品
3.    用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4.    可随时退出,退出时,打印已购买商品和余额

知识点:列表list、for循环、while循环、if判断

程序如下:

list列表的使用——购物车程序

list列表的使用——购物车程序

#输入余额
balance = int(input('Please input your balance:'))


#打印商品列表
product_list = [['Iphone', 8000], ['Max Pro', 12000], ['coffee', 30], ['fruit', 20]]
print('product list as below:')
for item in product_list:
    print(item)
print()


flag = True             #设置循环标志
shopping_cart = []      #定义存放购买商品的列表


#选择商品
while flag:
    index = input('Please enter the index of product:')
    
    #判断用户输入的是否是数字,如果是,则将该数字作为购买商品的索引,如果为q,则退出循环
    if index.isdigit():
        index = int(index)
        
        #判断输入的数字是否在列表的索引范围内,是否大于0
        if index > len(product_list) and index > 0:
            print('Invalid product!')
            
        #将余额同选择的商品价格做比较
        elif product_list[index-1][1] < balance:
            shopping_cart.append(product_list[index-1])       #将商品加入购物车
            balance = balance - product_list[index-1][1]      #余额减少
            print('Added succeed!')
            print("Your balance is %s" %balance)
            print()
        else:
            print("You don't have enough money!")
            print()
    
    elif index == 'q':
        flag = False           #修改循环标志为False


print('The list of your shopping cart: %s' %shopping_cart)

结果演示:

list列表的使用——购物车程序