购物车(2)优化代码

优化,更改为使用列表

# -*- coding: utf-8 -*-
# @Author: oppend
# @Date:   2017-07-27 19:43:59
# @Last Modified by:   oppend
# @Last Modified time: 2017-07-27 23:08:16
product_list = [('bike',1500),('tea',80),('computer',3500),('book',130)]
my_amount = input('您的资金(元):')
shopping_car = {}
shopcar = shopping_car.keys()
while True:
    print('>>>>>>>>>>>>商品列表<<<<<<<<<<<')
    for num,product in enumerate(product_list,1):
        print('[',num,']','=>','{0:<10}{1:>12}'.format(product[0],product[1]))
    print('-------------end---------------')

    choice = input('输入购买商品序号[q:退出]:')
    # 序号输入是否为数字
    if choice.isdigit():
        choice = int(choice)-1
        my_amount = int(my_amount)
        # 序号选择是否超出范围
        if 0 <= choice < len(product_list):
            choice_product = product_list[choice]
            product_name = str(choice_product[0])
            product_price = int(choice_product[1])
            # 金额是否足够
            if my_amount >= product_price:
                # 购物车是否存在商品
                if product_name not in shopcar:
                    shopping_car[product_name] = [product_price,1]
                else:
                    total = shopping_car[product_name][0] * 2
                    count = shopping_car[product_name][1] + 1
                    shopping_car[product_name] = [total,count]
                # 计算余额
                balane = my_amount - product_price
                print('购买了{0}x1,剩余金额{1}'.format(product_name,balane))
                my_amount = balane
            else:
                print('余额不足!')
                continue
        else:
            print('商品序号[{0}]不存在!'.format(choice+1))
            continue
    elif choice.lower() == 'q':
        if len(shopping_car) > 0:
            print('==========您已购买=========')
            for name in shopcar:
                price = shopping_car[name][0]
                product_num = shopping_car[name][1]
                print('{0:<10}{1:<15}x{2}'.format(name,price,product_num))
            print('===========================')
            break
    else:
        print('商品序号[{0}]错误!'.format(choice))
        continue
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的PHP购物车示例代码: 1. 添加商品到购物车 ```php <?php session_start(); // 模拟商品信息,实际应从数据库中获取 $products = array( array("id"=>"1", "name"=>"商品A", "price"=>10), array("id"=>"2", "name"=>"商品B", "price"=>20), array("id"=>"3", "name"=>"商品C", "price"=>30) ); // 获取要添加到购物车的商品ID $id = $_GET["id"]; // 查找对应的商品信息 foreach ($products as $product) { if ($product["id"] == $id) { // 将商品信息存储到Session中 $item = array( "id" => $product["id"], "name" => $product["name"], "price" => $product["price"], "quantity" => 1 ); if (isset($_SESSION["cart"])) { // 如果购物车已存在,直接添加商品 $_SESSION["cart"][$id] = $item; } else { // 如果购物车不存在,创建购物车并添加商品 $_SESSION["cart"] = array($id => $item); } break; } } // 跳转到购物车页面 header("location: cart.php"); ?> ``` 2. 显示购物车中的商品 ```php <?php session_start(); ?> <h1>购物车</h1> <table> <tr> <th>商品名称</th> <th>数量</th> <th>价格</th> <th>操作</th> </tr> <?php // 遍历购物车中的商品,并显示出来 if (isset($_SESSION["cart"])) { foreach ($_SESSION["cart"] as $item) { echo "<tr>"; echo "<td>" . $item["name"] . "</td>"; echo "<td>" . $item["quantity"] . "</td>"; echo "<td>" . $item["price"] . "</td>"; echo "<td><a href='remove.php?id=" . $item["id"] . "'>删除</a></td>"; echo "</tr>"; } } ?> <tr> <td colspan="2">总价:</td> <td colspan="2"> <?php // 计算购物车中所有商品的总价 $total = 0; if (isset($_SESSION["cart"])) { foreach ($_SESSION["cart"] as $item) { $total += $item["price"] * $item["quantity"]; } } echo $total; ?> </td> </tr> </table> ``` 3. 修改购物车中商品数量或删除商品 ```php <?php session_start(); // 获取要修改或删除的商品ID $id = $_GET["id"]; // 判断用户是要修改数量还是删除商品 if ($_GET["action"] == "update") { // 更新商品数量 $quantity = $_POST["quantity"]; $_SESSION["cart"][$id]["quantity"] = $quantity; } else if ($_GET["action"] == "delete") { // 删除商品 unset($_SESSION["cart"][$id]); } // 跳转回购物车页面 header("location: cart.php"); ?> ``` 以上是一个简单的PHP购物车示例代码,具体实现方式还可以根据需求进行调整和优化。需要注意的是,实际应用中还需要考虑安全性、性能、用户体验等方面的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值