# 实现在线购物系统:计算商品总价并输出结果


背景介绍

在线购物系统的核心功能是处理用户输入的商品名称和数量,计算并输出商品总价。该系统需要支持以下功能:

  1. 输入商品名称和数量的文本处理
  2. 数据计算(名称×数量)
  3. 存储商品信息(文件读写)
  4. 输出结果(总价)

通过Python语言实现,系统可本地运行,支持简单配置和动态数据存储。

系统实现思路

1. 文件读写与数据存储

  • 文件存储:使用Python内置的open()函数读取配置文件(如products.txt),存储商品列表,支持动态更新。
  • 数据结构:使用字典或列表保存商品名称和价格,便于后续处理。

2. 输入处理与数据计算

def calculate_total(price_list, quantity):
    total = sum(price * quantity for price, quantity in price_list)
    return round(total, 2)

def main():
    with open("products.txt", "r") as file:
        products = [line.strip() for line in file]

    print("输入商品名称和数量:")
    item_name = input("请输入商品名称(如:苹果 2):").strip()
    quantity = input("请输入数量(如:3):").strip()

    price_list = [item_name, int(quantity)]  # 存储为元组

    total = calculate_total(price_list, int(quantity))
    print(f"总价:{total} 元")

3. 输出结果验证

  • 输出总价时使用print语句,并对结果进行四舍五入,确保格式正确。
  • 输入验证:检查输入是否为字符串,数量为整数,防止无效数据。

4. 结束总结

通过Python实现,系统能够支持文本输入和数据计算,实现简单配置和动态数据存储。代码中使用with语句进行文件读写,确保可运行性。所有功能均通过注释说明实现原理,确保可理解性。

示例实现代码

import sys

def calculate_total(price_list, quantity):
    total = sum(price * quantity for price, quantity in price_list)
    return round(total, 2)

def main():
    with open("products.txt", "r") as file:
        products = [line.strip() for line in file]

    print("输入商品名称和数量:")
    item_name = input("请输入商品名称(如:苹果 2):").strip()
    quantity = input("请输入数量(如:3):").strip()

    price_list = [item_name, int(quantity)]  # 存储为元组

    total = calculate_total(price_list, int(quantity))
    print(f"总价:{total} 元")

if __name__ == "__main__":
    main()

技术实现要点

  • 文件读写:使用with语句读取和写入文件,确保可执行性。
  • 数据结构:使用元组存储商品信息,便于后续处理。
  • 输入验证:确保输入数据为字符串且数量为整数,避免无效数据。
  • 输出格式:使用print语句输出总价,并对结果进行四舍五入。

该实现支持本地运行,具备良好的可维护性和可扩展性。


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注