python购物车结算编写_python3 模拟商品购物车及商品结算

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-17 00:07   31   0

#!/usr/bin/env python

# -*- coding:utf-8 -*-

#将商品加入购物车及商品结算

a=input('请输入总资产:')

car_dict={}

goods=[{"name":"电脑","price":4999},

{"name":"电视", "price": 2559},

{"name":"平板", "price": 1888},

{"name":"手机", "price": 2449}]

#显示所有是商品及其价格

for i in goods:

print(i['name'], i['price'])

#用户输入商品加入购物车,输入Y/y就结算

while True:

i2=input("请输入商品名称(Y/y结算):")

if i2.lower()=="y":

break

#如果用户输入的的商品在商品列表,将用户所选的商品数及其单价更新到car_dict这个字典里

for items in goods:

if items['name']==i2:

name=items['name']

if name in car_dict.keys():

car_dict[name]['num']=car_dict[name]['num']+1

else:

car_dict[name] = {"num":1,"single_price":items['price']}

print(car_dict)

#结算部分,对比用户总资产和所选商品的总价格,分别输出对应的提示

total_price=0

for k,v in car_dict.items():

m=v['single_price']

n=v['num']

all_sum=m*n

total_price=total_price+all_sum

if total_price>int(a):

print("sorry,your asset is too little")

else:

print("Congratulation,buy them successfully!")

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP