Python实战从零构建购物车与登录系统刚学完Python基础语法的新手常会遇到一个困境看懂了变量、循环和函数却不知道如何把它们组合成一个完整的项目。本文将带你用Python构建两个实用的小系统——购物车和用户登录通过真实场景的代码实践打通从理论到应用的最后一公里。1. 项目环境准备与设计思路在开始编码前我们需要明确项目的核心功能和实现路径。这两个系统虽然规模不大但包含了数据处理、逻辑判断和用户交互等编程核心要素。1.1 开发环境配置确保你的电脑已安装Python 3.6推荐3.9版本任意代码编辑器VS Code/PyCharm等# 检查Python版本 python --version1.2 项目架构设计购物车系统需要实现商品信息存储用户输入处理金额计算与显示登录系统需要包含用户认证流程多条件验证错误提示机制2. 购物车系统实现让我们先构建一个功能完整的购物车系统它不仅能计算总价还能记录购买历史和提供折扣功能。2.1 基础版本实现# 商品数据库 products { apple: {price: 6.6, stock: 100}, orange: {price: 5, stock: 80}, banana: {price: 3.5, stock: 60} } def calculate_total(cart): total 0 for item, quantity in cart.items(): total products[item][price] * quantity return round(total, 2) def display_products(): print(\n可用商品列表:) for idx, (name, info) in enumerate(products.items(), 1): print(f{idx}. {name}: ¥{info[price]}/份 (库存:{info[stock]})) def shopping_cart(): cart {} while True: display_products() choice input(请输入商品编号加入购物车(q结算): ) if choice.lower() q: break try: selected list(products.keys())[int(choice)-1] quantity float(input(f请输入{selected}的购买数量: )) if quantity products[selected][stock]: cart[selected] cart.get(selected, 0) quantity products[selected][stock] - quantity print(f已添加 {quantity}份 {selected} 到购物车) else: print(库存不足!) except (ValueError, IndexError): print(无效输入请重试) if cart: print(\n 购物清单 ) for item, quantity in cart.items(): print(f{item}: {quantity}份 x ¥{products[item][price]} ¥{quantity*products[item][price]:.2f}) print(f总计: ¥{calculate_total(cart)}) else: print(您没有购买任何商品) if __name__ __main__: shopping_cart()2.2 功能扩展与优化基础版本已经可用但我们还可以增加更多实用功能折扣系统def apply_discount(total): if total 100: return total * 0.9 # 9折 elif total 50: return total * 0.95 # 95折 return total购买历史记录import json import datetime def save_history(cart, total): history { date: datetime.datetime.now().strftime(%Y-%m-%d %H:%M), items: cart, total: total } with open(purchase_history.json, a) as f: f.write(json.dumps(history) \n)库存预警def check_stock(): for name, info in products.items(): if info[stock] 10: print(f警告: {name}库存仅剩{info[stock]}!)3. 用户登录系统开发接下来我们构建一个更安全的登录系统包含验证码、密码加密和登录限制等功能。3.1 基础登录验证import getpass # 用于安全输入密码 users { admin: { password: 123456, locked: False, attempts: 0 } } def generate_captcha(): import random chars abcdefghijkmnpqrstuvwxyz23456789 return .join(random.choice(chars) for _ in range(4)) def login_system(): captcha generate_captcha() print(f验证码: {captcha}) username input(用户名: ) password getpass.getpass(密码: ) # 隐藏输入 input_captcha input(请输入验证码: ) if input_captcha.lower() ! captcha.lower(): print(验证码错误!) return False if username in users: if users[username][locked]: print(账户已锁定请联系管理员) return False if password users[username][password]: users[username][attempts] 0 print(登录成功!) return True else: users[username][attempts] 1 if users[username][attempts] 3: users[username][locked] True print(错误次数过多账户已锁定) else: print(f密码错误! 剩余尝试次数: {3 - users[username][attempts]}) else: print(用户名不存在) return False if __name__ __main__: login_system()3.2 安全增强措施密码加密存储import hashlib def encrypt_password(password): return hashlib.sha256(password.encode()).hexdigest() # 使用时替换 # if encrypt_password(password) users[username][password]:登录日志记录def log_login_attempt(username, success): with open(login_log.txt, a) as f: status 成功 if success else 失败 f.write(f{datetime.datetime.now()}: {username} 登录{status}\n)密码强度检查def check_password_strength(password): if len(password) 8: return 密码至少需要8个字符 if not any(c.isupper() for c in password): return 密码需要包含大写字母 if not any(c.isdigit() for c in password): return 密码需要包含数字 return None4. 项目调试与优化技巧完成基础功能后我们需要确保代码的健壮性和用户体验。4.1 异常处理实践def safe_float_input(prompt): while True: try: return float(input(prompt)) except ValueError: print(请输入有效的数字) # 在购物车中替换 # quantity safe_float_input(f请输入{selected}的购买数量: )4.2 代码重构建议将功能模块化class ShoppingCart: def __init__(self): self.products {...} self.cart {} def add_item(self, product_id, quantity): # 添加商品逻辑 def calculate_total(self): # 计算总价逻辑使用配置文件# config.json { products: { apple: {price: 6.6, stock: 100}, ... }, max_login_attempts: 3 }单元测试示例import unittest class TestShoppingCart(unittest.TestCase): def setUp(self): self.cart ShoppingCart() def test_add_item(self): self.cart.add_item(apple, 2) self.assertEqual(self.cart.cart[apple], 2) if __name__ __main__: unittest.main()4.3 性能优化技巧使用集合快速查找valid_usernames set(users.keys()) if username not in valid_usernames: # 比列表查找更快减少数据库访问# 批量更新而不是单条更新 def update_stock(cart): for product_id, quantity in cart.items(): products[product_id][stock] - quantity使用缓存机制from functools import lru_cache lru_cache(maxsize32) def get_product_info(product_id): return products.get(product_id)