python购物车作业

时间:2022-03-18 17:14:15
# -*- coding:utf8 -*-
# Author:Wang Yao
goods = [{"name": "电脑", "price": 1999},
         {"name": "鼠标", "price": 10},
         {"name": "游艇", "price": 20},
         {"name": "美女", "price": 998},]  #定义一个商品列表
print('###欢迎来到购物商城###'.center(30))
shopping_car = {} #定义一个字典为空购物车
#money = input('请输入你的金额:').strip()
while True:
    money = input('请输入你的金额:').strip()
    if money.isdigit() and int(money) > 0: #判断输入的金额是否大于0
        print('请选择购买以下商品:')
        for i,k in enumerate(goods): #枚举将其组成一个索引序列,利用它可以同时获得索引和值
            print('{} {} {}'.format(i,k['name'],k['price']))
        choice = input('请输入你想购买的商品编号:')
        if choice.isdigit() and int(choice) < len(goods):
            num = input('你要购买的商品数量是:')
            if num.isdigit():#判断有没有钱购买
                if int(money) > goods[int(choice)]['price'] * int(num):
                    money = int(money) - goods[int(choice)]['price'] * int(num)
                    if goods[int(choice)]['name'] in shopping_car: #判断商品在不在购物车里
                        shopping_car[goods[int(choice)]['name']] = shopping_car[goods[int(choice)]['name']] + int(num)
                    else:
                        shopping_car[goods[int(choice)]['name']] = int(num) #在字典里新建了一对键值对
                    print('购物车中的商品有{},你的余额为{}'.format(shopping_car,money))
                    break
                else:
                    print('抱歉,你的金额不够!')
                    break
        else:
            print('你输入的有误')
    else:
        print('你输入的有误')