python---购物车

本文介绍了一个简单的购物车程序实现过程,使用 Python 编写。该程序允许用户输入薪资,并从预定义的商品列表中选择购买商品。程序会跟踪用户的购买行为并实时更新剩余薪资。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现购物车:

#!/usr/bin/env python
#coding:utf-8
__author__ = "lvah"
'''
@author:wangjiazhuo
@file:购物车.py
@contact:pucca@163.com
@time:7/12/176:23 PM
@desc:
'''
salary = raw_input('input your salary:')
if salary.isdigit():
    salary = int(salary)
shop_car = []
mall = [
    ('Ipone',8000),
    ('Book',200),
    ('Bike',1000)
]
for item in enumerate(mall):
    num = item[0]
    name = item[1][0]
    price = item[1][1]
    print num, name, price
while True:
    choice = raw_input('choose you want to buy:      q to exit')
    if choice.isdigit():
        choice = int(choice)
        if choice <= len(mall)-1:
            p_item = mall[choice]
            if salary < p_item[1]:
                print '余额不足,请购买其他商品或退出'
            elif salary > 0:
                shop_car.append(p_item)
                salary -= p_item[1]
                print '\n你买到的商品有:',
                for item in shop_car:
                    print item
                print '你的余额为:%d'%salary
            else:
                pass
        else:
            print '请输入已有的商品编号'
    elif choice == 'q':
        print '\n你买到的商品有:'
        for item in shop_car:
            print item
        print '你的余额为:%d'%salary
        exit(0)
    else:
        print '请重新选择'

执行结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值