Python实现商场购物

Python做一个商场购物代码运行后有
登录
注册
退出
注册成功后可以登录,登录成功后会有充值,充值成功后去选择购物
查询余额
充值
查看商品,最少十个可以添加的物品
添加商品到购物车
购物车

进入购物车后购物车里面可以查看
已经选择的商品,修改商品的数量,删除商品,结算,结算后显示余额,询问手机号和地址,


class User:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.cart = []

    def add_to_cart(self, item, price):
        self.cart.append((item, price))

    #移除,输入想要删除的商品id和数量
    def remove_from_cart(self, id, count):
        for i in range(count):
            self.cart.remove(self.cart[id])

    def check_balance(self):
        print(f"当前余额为: {self.balance}")


class ShoppingMarket:
    def __init__(self):
        self.users = {}
        #10个商品
        self.products = {1:("苹果", 10),  2:("香蕉", 20),  3:("橘子", 30),  4:("梨", 40),  5:("葡萄", 50),  6:("西瓜", 60),  7:("芒果", 70),  8:("榴莲", 80),  9:("火龙果", 90),  10:("草莓", 100)}

    def register(self, name, password):
        self.users[name] = User(name, 0)

    def login(self, name, password):
        if name in self.users:
            self.current_user = self.users[name]
            return True
        return False

    def add_balance(self, amount):
        self.current_user.balance += amount

    def show_cart(self):
        print("购物车:")
        for item, price in self.current_user.cart:
            print(f"{item}: {price}")

    def show_products(self):
        print("所有商品:")
        for id, (item, price) in self.products.items():
            print(f"{id}. {item}: {price}")

    def buy(self, id, count, price):
        for i in range(count):
            self.current_user.add_to_cart(self.products[id][0], price)

    # 移除,输入想要删除的商品id和数量
    def remove_from_cart(self, id, count):
        for i in range(count):
            self.current_user.cart.remove(self.current_user.cart[id])

    # 结账,写地址和电话后扣除余额,余额不足则提示;结账完成后,显示购买的商品的手机号和地址,提示结账成功,清空购物车
    def checkout(self, address, phone):
        total_price = 0
        for item, price in self.current_user.cart:
            total_price += price
        if total_price > self.current_user.balance:
            print("余额不足")
        else:
            self.current_user.balance -= total_price
            print("结账成功")
            print("购买的商品为:", item)
            #余额:收货地址为:手机号:
            print("余额:", self.current_user.balance, "收货地址为:", address, "手机号:", phone)
            self.current_user.cart = []

    def run(self):

        while True:
            print("1. 注册")
            print("2. 登录")
            print("3. 退出")
            choice = input("请输入选项: ")
            if choice == "1":
                name = input("请输入用户名: ")
                password = input("请输入密码: ")
                self.register(name, password)
            elif choice == "2":
                name = input("请输入用户名: ")
                password = input("请输入密码: ")
                if self.login(name, password):
                    while True:
                        print("1. 查看余额")
                        print("2. 充值")
                        print("3. 查看购物车")
                        print("4. 查看所有商品")
                        print("5. 添加商品到购物车")
                        print("6. 从购物车删除商品")
                        print("7. 结账")
                        print("8. 退出")
                        choice = input("请输入选项: ")
                        if choice == "1":
                            self.current_user.check_balance()
                        elif choice == "2":
                            amount = int(input("请输入充值金额: "))
                            self.add_balance(amount)
                        elif choice == "3":
                            self.show_cart()
                        elif choice == "4":
                            self.show_products()
                        elif choice == "5":
                            id = int(input("请输入商品id: "))
                            count = int(input("请输入商品数量: "))
                            price = self.products[id][1]
                            self.buy(id, count, price)
                        elif choice == "6":
                            id = int(input("请输入移除的商品id: "))
                            count = int(input("请输入移除的商品数量: "))
                            self.remove_from_cart(id, count)
                        elif choice == "7":
                            address = input("请输入地址: ")
                            phone = input("请输入电话: ")
                            self.checkout(address, phone)
                        elif choice == "8":
                            break
            elif choice == "3":
                break


if __name__ == "__main__":
    market = ShoppingMarket()
    market.run()

有点难

好家伙,我怎么好像做过呢

代码如下:


```python
# define a dictionary to store the users' information
users = {}
# define a list to store the items in the shopping cart
cart = []

def register():
  username = input("Please enter a username:")
  password = input("Please enter a password:")
  users[username] = {"password": password, "balance": 0}
  print("Registration successful.")

def login():
  username = input("Please enter your username:")
  password = input("Please enter your password:")
  if username in users and users[username]["password"] == password:
    print("Login successful.")
    return True
  else:
    print("Login failed. Incorrect username or password.")
    return False

def recharge():
  username = input("Please enter your username:")
  if username in users:
    amount = int(input("Please enter the amount you want to recharge:"))
    users[username]["balance"] += amount
    print("Recharge successful. Your current balance is", users[username]["balance"])
  else:
    print("User not found.")

def show_balance(username):
  if username in users:
    print("Your current balance is", users[username]["balance"])
  else:
    print("User not found.")

def add_to_cart(item):
  cart.append(item)
  print("Item added to the cart.")

def show_cart():
  if len(cart) == 0:
    print("The cart is empty.")
  else:
    print("The items in the cart are:")
    for item in cart:
      print(item)

def checkout(username):
  if username in users:
    total_price = 0
    for item in cart:
      total_price += item["price"]
    if users[username]["balance"] >= total_price:
      users[username]["balance"] -= total_price
      print("Checkout successful. Your current balance is", users[username]["balance"])
      phone_number = input("Please enter your phone number:")
      address = input("Please enter your address:")
      print("Order placed successfully. Phone number:", phone_number, "Address:", address)
    else:
      print("Not enough balance.")
  else:
    print("User not found.")

def main():
  while True:
    print("Welcome to the shopping mall.")
    print("1. Register")
    print("2. Login")
    print("3. Recharge")
    print("4. Exit")
    choice = int(input("Please enter your choice:"))
    if choice == 1:
      register()
    elif choice == 2:
      if login():
        while True:
          print("1. Show balance")
          print("2. Show items")
          print("3. Add to cart")
          print("4. Show cart")
          print("5. Checkout")


```

img

img

img

img

img

img


分别实现用户定义
登录和注册
充值
定义商品
商品添加
查询余额查看商品
添加商品到购物车

img


以上引用来自ChatGPT

参考代码:

# 菜单一
# 1.登录
def login(username, passwd):
    if username in user and user[username]['passwd'] == passwd:
        return True

# 2.注册
def register(username, passwd, money):
    if username in user:
        print("用户名已存在,请重新输入!")
    else:
        user[username] = {'passwd':passwd, 'money':money}
        print(f"{username}注册成功")
        print("用户信息已更新".center(26,"-"))
        print(f"{'用户名':<8}{'密码':<10}{'金额':<7}")
        for i in user:      #逐个打印用户名、密码、金额
            print(f"{i:<10}{user[i]['passwd']:<12}{user[i]['money']:<10}")

# 菜单二
# 1.查看商品信息
def message():
    print("商品信息".center(40,"-"))
    print(f"{'商品编号':<7}{'商品名称':<8}{'单价':<7}")
    for i in goodsmess:     #逐个打印商品编号、名称、单价
        print(f"{i:<10}{goodsmess[i]['name']:<10}{goodsmess[i]['price']:<10}")
    print("-"*44)

# 2.购买商品,将商品加入购物车
def add_goods(goodsid, goodsnum):
    # cart初始化为空字典{} --> {goodsid:goodsnum}
    # 若购物车里已经有该商品,该商品数量在原基础上增加即可
    cart[goodsid] = cart.get(goodsid, 0) + goodsnum
    print("加购成功...")
    print(f"{'商品编号':<8}{'数量':<7}")
    print(f"{goodsid:<12}{goodsnum:<10}")    #打印此次加购的商品信息:商品编号、数量

# 3.查看、结算购物车
# 3.1查看所有加购成功的商品
def check_cart():
    print("查看购物车".center(38,"-"))
    print(f"{'商品编号':<8}{'商品名称':<8}{'单价':<7}{'数量':<7}")
    for i in cart:             #逐个打印商品编号、名称、单价、数量
        print(f"{i:<11}{goodsmess[i]['name']:<10}{goodsmess[i]['price']:<8}{cart[i]:<10}")
    print("-"*41)

# 3.2结算购物车
def pay_cart(pay):
    global cartmoney, cartmoney2
    for i in cart:
        cartmoney += cart[i] * goodsmess[i]['price']
    if cartmoney <= user[username]['money'] :
        user[username]['money'] -= cartmoney
        print(f"结算成功,本次消费:{cartmoney},余额:{user[username]['money']}")
        cart2.update(cart.copy())    #清空cart之前先保存,退出时,输出所有已购商品 --》购物车1+购物车2+...
        cart.clear()            #结算成功,清空购物车
        cartmoney2 += cartmoney     #将每次的消费金额相加,退出时输出
        cartmoney = 0        #购物车清空之后,将消费金额置0,可继续加购,结算购物车
    else:
        print(f"余额不足!")

# 4.退出
# 退出并打印购物单和余额
def exit():
    global cartmoney2
    print("谢谢惠顾!欢迎下次光临!".center(30))
    print("-"*38)
    print(f"{'商品编号':<8}{'商品名称':<8}{'单价':<7}{'数量':<7}")
    for i in cart2:
        print(f"{i:<11}{goodsmess[i]['name']:<10}{goodsmess[i]['price']:<8}{cart2[i]:<10}")
    print("-" * 38)
    print(f"总共消费:{cartmoney2},余额为:{user[username]['money']}")
    cart2.clear()   #退出之后清空购物单
    cartmoney2 = 0     #将总消费金额置0

# 主程序
user = {'root':{'passwd':'123456', 'money':100}}
print("欢迎进入三乐购物系统".center(50,"-"))
goodsmess = {'F01':{'name':'苹果','price':2},
             'F02':{'name':'香蕉','price':2},
             'F03':{'name':'梨子','price':1},
             'F04':{'name':'芒果','price':2},
             'F05':{'name':'柚子','price':8},
             'F06':{'name':'西瓜','price':10}}

# cart = {goodsid:goodsnum} -->  {'编号':'数量'}
cart = {}      #购物车,初始化为空
cart2 = {}     #存放所有已购商品 --> 类似于购物车1+购物车2+...
cartmoney = 0     #购物车消费金额  初始化为0
cartmoney2 = 0    #所有的购物车消费金额
while 1:
    print("1、登录".center(50))
    print("2、注册".center(50))
    print("3、退出".center(50))
    option = input("请输入你的选择:")
    if option == '1':
        username = input("请输入用户名:")
        passwd = input("请输入密码:")
        if login(username,passwd):
            print("登录成功")
            print(f"欢迎光临!你的余额为:{user[username]['money']}")
            while 2:
                print("1、查看商品信息".center(50))
                print("2、购买商品,将商品加入购物车".center(58))
                print("3、查看和结算购物车".center(52))
                print("4、退出".center(46))
                option2 = input("请输入你的选择:")
                if option2 == '1':
                    message()
                elif option2 == '2':
                    goodsid = input("请输入你想加购的商品编号(F01~F06):")
                    if goodsid in goodsmess:     #输入的编号存在
                        goodsnum = input("请输入你想加购的商品数量:")
                        if goodsnum.isdigit():
                            goodsnum = int(goodsnum)
                            add_goods(goodsid, goodsnum)
                        else:
                            print("输入的不是整数")
                    else:
                        print("商品不存在!")
                elif option2 == '3':
                    check_cart()
                    pay = input("结算购物车请按1(按其他键返回菜单):")
                    if pay == '1':
                        pay_cart(pay)
                elif option2 == '4':
                    print("退出")
                    exit()
                    break
                else:
                    print("输入错误!")
        else:
            print("登录失败")
    elif option == '2':
        username = input("请输入用户名:")
        passwd = input("请输入密码:")
        money = int(input("请输入金额:"))
        register(username,passwd,money)
    elif option == '3':
        print("退出")
        break
    else:
        print("输入错误!")

好家伙,这次我专业对口了,点击我的昵称就行

根据您描述的问题,希望用python实现网上购物商场系统,这里给您找到一些资料,包含源码,您可以拿来修改修改:
1.基于Python的网上购物商场系统的设计与实现
https://blog.csdn.net/lingpao1688/article/details/120320864
2.https://github.com/mirumee/saleor
3.基于Python的购物商城管理系统
https://github.com/kongxiangchx/Shopping-mall-management-system