本文目录导读:

我来详细介绍如何使用Python模拟真实场景,从基础到进阶的实用案例:
电商系统模拟
购物车模拟
import random
from datetime import datetime, timedelta
import json
class ShoppingCart:
def __init__(self):
self.items = {}
self.user_actions = []
def add_item(self, product_id, name, price, quantity=1):
"""添加商品到购物车"""
if product_id in self.items:
self.items[product_id]['quantity'] += quantity
else:
self.items[product_id] = {
'name': name,
'price': price,
'quantity': quantity,
'added_time': datetime.now()
}
self.log_action('add', product_id, quantity)
print(f"✅ 添加 {name} x{quantity} 到购物车")
def remove_item(self, product_id, quantity=1):
"""移除购物车商品"""
if product_id in self.items:
if self.items[product_id]['quantity'] <= quantity:
del self.items[product_id]
else:
self.items[product_id]['quantity'] -= quantity
self.log_action('remove', product_id, quantity)
print(f"❌ 从购物车移除商品")
def calculate_total(self):
"""计算总计金额"""
total = sum(item['price'] * item['quantity']
for item in self.items.values())
return total
def apply_promotion(self, promo_code):
"""应用优惠券"""
promotions = {
'SAVE10': 0.1, # 10% off
'SAVE20': 0.2, # 20% off
'NEW50': 50 # 固定减免50元
}
if promo_code in promotions:
discount = promotions[promo_code]
if isinstance(discount, float):
total = self.calculate_total()
return int(total * (1 - discount))
else:
return max(0, self.calculate_total() - discount)
return self.calculate_total()
def log_action(self, action, product_id, quantity):
"""记录用户行为"""
self.user_actions.append({
'action': action,
'product_id': product_id,
'quantity': quantity,
'timestamp': datetime.now()
})
# 模拟用户购物行为
def simulate_shopping():
cart = ShoppingCart()
# 模拟商品数据库
products = [
{'id': 1, 'name': 'Python编程书', 'price': 89},
{'id': 2, 'name': '机械键盘', 'price': 299},
{'id': 3, 'name': '显示器', 'price': 1599},
{'id': 4, 'name': '鼠标垫', 'price': 49}
]
# 模拟用户操作
user_actions = [
('add', 1, 2), # 添加2本书
('add', 2, 1), # 添加1个键盘
('add', 3, 1), # 添加1个显示器
('remove', 1, 1), # 移除1本书
('add', 4, 3), # 添加3个鼠标垫
]
print("🛒 开始模拟购物")
for action, product_id, qty in user_actions:
product = next(p for p in products if p['id'] == product_id)
if action == 'add':
cart.add_item(product_id, product['name'], product['price'], qty)
elif action == 'remove':
cart.remove_item(product_id, qty)
# 计算最终价格
total = cart.calculate_total()
final_price = cart.apply_promotion('SAVE10')
print(f"\n💰 原始总价: ¥{total}")
print(f"🎉 优惠后价格: ¥{final_price}")
print(f"💾 节省: ¥{total - final_price}")
simulate_shopping()
ATM银行系统模拟
import time
import random
from datetime import datetime
class BankAccount:
def __init__(self, account_number, owner_name, initial_balance=0):
self.account_number = account_number
self.owner_name = owner_name
self.balance = initial_balance
self.transaction_history = []
self.daily_limit = 20000
self.daily_withdrawn = 0
def deposit(self, amount):
"""存款"""
if amount <= 0:
raise ValueError("存款金额必须大于0")
self.balance += amount
self._record_transaction('存款', amount)
print(f"✅ 存款 ¥{amount} 成功")
self._validate_money_laundering(amount)
def withdraw(self, amount):
"""取款"""
if amount <= 0:
raise ValueError("取款金额必须大于0")
if amount > self.balance:
raise ValueError("余额不足")
if self.daily_withdrawn + amount > self.daily_limit:
raise ValueError("超过每日提款限额")
# 模拟ATM出钞时间
print("💰 正在出钞...")
time.sleep(1)
self.balance -= amount
self.daily_withdrawn += amount
self._record_transaction('取款', amount)
print(f"✅ 取款 ¥{amount} 成功,请收好现金")
def transfer(self, target_account, amount):
"""转账"""
if amount <= 0:
raise ValueError("转账金额必须大于0")
if amount > self.balance:
raise ValueError("余额不足,无法转账")
# 大额转账需要验证
if amount > 50000:
self._large_transfer_verification()
self.balance -= amount
target_account.balance += amount
self._record_transaction(f'转账至 {target_account.owner_name}', amount)
target_account._record_transaction(f'收到来自 {self.owner_name} 的转账', amount)
print(f"📤 成功转账 ¥{amount} 至 {target_account.owner_name}")
def _large_transfer_verification(self):
"""大额转账验证"""
print("⚠️ 检测到大额转账,需要二次验证")
code = random.randint(100000, 999999)
print(f"验证码: {code}")
user_input = input("请输入验证码: ")
if int(user_input) != code:
raise ValueError("验证码错误,转账取消")
def _validate_money_laundering(self, amount):
"""反洗钱检测"""
if amount > 100000:
print("⚠️ 警告:大额存款已记录,需向央行报告")
def _record_transaction(self, action, amount):
"""记录交易"""
self.transaction_history.append({
'action': action,
'amount': amount,
'balance_after': self.balance,
'timestamp': datetime.now()
})
def show_balance(self):
"""显示余额"""
print(f"💳 账户余额: ¥{self.balance}")
return self.balance
# 模拟ATM操作
def atm_simulation():
print("🏦 欢迎使用银行模拟系统")
# 创建账户
acc1 = BankAccount("6222021234567890", "张三", 100000)
acc2 = BankAccount("6222020987654321", "李四", 5000)
# 模拟操作
while True:
print("\n请选择操作:")
print("1. 查询余额")
print("2. 存款")
print("3. 取款")
print("4. 转账")
print("5. 交易记录")
print("6. 退出")
choice = input("请选择(1-6): ")
if choice == '1':
acc1.show_balance()
elif choice == '2':
amount = float(input("存款金额: "))
acc1.deposit(amount)
elif choice == '3':
amount = float(input("取款金额: "))
acc1.withdraw(amount)
elif choice == '4':
amount = float(input("转账金额: "))
acc1.transfer(acc2, amount)
elif choice == '5':
print("交易记录:")
for trans in acc1.transaction_history[-5:]: # 显示最近5条
print(f" {trans['timestamp'].strftime('%H:%M:%S')} - {trans['action']}: ¥{trans['amount']}")
elif choice == '6':
print("谢谢使用,再见!")
break
# atm_simulation() # 取消注释运行ATM模拟
天气预报模拟
import requests
import json
from datetime import datetime
import time
class WeatherSimulator:
def __init__(self):
self.weather_conditions = {
'晴天': {'温度范围': (25, 35), '湿度': (30, 50)},
'多云': {'温度范围': (20, 30), '湿度': (40, 70)},
'阴天': {'温度范围': (15, 25), '湿度': (60, 85)},
'小雨': {'温度范围': (18, 25), '湿度': (70, 95)},
'大雨': {'温度范围': (15, 22), '湿度': (80, 99)},
'雪天': {'温度范围': (-10, 5), '湿度': (60, 80)}
}
def generate_weather(self, city, date=None):
"""模拟生成天气预报"""
import random
# 根据不同城市生成不同的天气
city_weather_probability = {
'北京': {'晴天': 0.4, '多云': 0.3, '阴天': 0.2, '小雨': 0.1},
'上海': {'晴天': 0.2, '多云': 0.3, '阴天': 0.2, '小雨': 0.2, '大雨': 0.1},
'广州': {'晴天': 0.3, '多云': 0.2, '小雨': 0.3, '大雨': 0.2},
'哈尔滨': {'晴天': 0.3, '多云': 0.2, '阴天': 0.2, '小雨': 0.1, '雪天': 0.2}
}
if city in city_weather_probability:
conditions = list(city_weather_probability[city].keys())
probabilities = list(city_weather_probability[city].values())
weather = random.choices(conditions, probabilities)[0]
else:
weather = random.choice(list(self.weather_conditions.keys()))
# 获取该天气下的数据范围
weather_data = self.weather_conditions[weather]
temp = random.randint(*weather_data['温度范围'])
humidity = random.randint(*weather_data['湿度'])
# 生成风力等级
wind_level = random.randint(1, 5)
wind_direction = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'][random.randint(0, 7)]
return {
'city': city,
'date': date or datetime.now().strftime('%Y-%m-%d'),
'weather': weather,
'temperature': temp,
'humidity': humidity,
'wind': f"{wind_direction}风 {wind_level}级",
'uv_index': random.randint(1, 10)
}
def get_clothing_suggestion(self, temp, weather):
"""根据天气推荐穿衣"""
suggestion = []
if temp < 0:
suggestion.extend(['羽绒服', '棉裤', '帽子', '手套'])
elif temp < 10:
suggestion.extend(['厚外套', '毛衣', '秋裤'])
elif temp < 20:
suggestion.extend(['夹克', '长袖衬衫'])
else:
suggestion.extend(['短袖', '短裤'])
if '雨' in weather:
suggestion.append('雨伞')
if '雪' in weather:
suggestion.append('防滑鞋')
return '、'.join(suggestion)
def display_weather(self, weather_data):
"""显示天气预报"""
print(f"\n🌍 {weather_data['city']}天气预报")
print(f"📅 日期: {weather_data['date']}")
print(f"{"━"*30}")
print(f"☁️ 天气: {weather_data['weather']}")
print(f"🌡️ 温度: {weather_data['temperature']}°C")
print(f"💧 湿度: {weather_data['humidity']}%")
print(f"🌬️ 风力: {weather_data['wind']}")
print(f"☀️ 紫外线: {weather_data['uv_index']}/10")
print(f"\n👔 穿衣建议: {self.get_clothing_suggestion(weather_data['temperature'], weather_data['weather'])}")
# 模拟实时天气更新
def weather_simulation():
simulator = WeatherSimulator()
cities = ['北京', '上海', '广州', '哈尔滨', '成都']
print("🌤️ 实时天气预报")
print("每天更新3次天气信息\n")
# 模拟一周天气趋势
for day in range(7):
print(f"\n{"="*40}")
print(f"第{day+1}天天气预测")
print(f"{'='*40}")
for city in cities:
weather_data = simulator.generate_weather(city, f"2024-01-{day+1:02d}")
simulator.display_weather(weather_data)
weather_simulation()
餐厅点餐系统模拟
import threading
import time
import random
from queue import Queue
from datetime import datetime
class Dish:
def __init__(self, name, price, prep_time):
self.name = name
self.price = price
self.prep_time = prep_time # 准备时间(秒)
class Order:
def __init__(self, order_id, table_id, dishes):
self.order_id = order_id
self.table_id = table_id
self.dishes = dishes
self.status = 'pending'
self.created_at = datetime.now()
class Restaurant:
def __init__(self, name, max_tables=5):
self.name = name
self.menu = self._init_menu()
self.orders = Queue()
self.tables = {i: None for i in range(1, max_tables+1)}
self.kitchen = Kitchen(self)
def _init_menu(self):
"""初始化菜单"""
return {
'宫保鸡丁': Dish('宫保鸡丁', 38, 12),
'麻婆豆腐': Dish('麻婆豆腐', 28, 8),
'红烧肉': Dish('红烧肉', 58, 20),
'清蒸鲈鱼': Dish('清蒸鲈鱼', 68, 15),
'蒜蓉空心菜': Dish('蒜蓉空心菜', 22, 6),
'米饭': Dish('米饭', 3, 0),
'酸辣汤': Dish('酸辣汤', 18, 10)
}
def display_menu(self):
"""显示菜单"""
print(f"\n🍽️ {self.name} 菜单")
print("=" * 40)
for name, dish in self.menu.items():
print(f"{name:12} ¥{dish.price:3d} (准备时间: {dish.prep_time}秒)")
def take_order(self, table_id, dishes_name):
"""接受订单"""
if self.tables.get(table_id) is None:
self.tables[table_id] = []
dishes = []
for dish_name in dishes_name:
if dish_name in self.menu:
dishes.append(self.menu[dish_name])
if dishes:
order = Order(
order_id=datetime.now().timestamp(),
table_id=table_id,
dishes=dishes
)
self.orders.put(order)
self.tables[table_id].append(order)
print(f"📝 桌号{table_id} 订单已提交: {', '.join(d['name'] for d in dishes)}")
return True
return False
class Kitchen:
def __init__(self, restaurant):
self.restaurant = restaurant
self.chef_count = 2
self.is_running = False
def start_cooking(self):
"""开始处理订单"""
self.is_running = True
for i in range(self.chef_count):
chef_thread = threading.Thread(target=self._cook, args=(f"厨师-{i+1}",))
chef_thread.start()
def _cook(self, chef_name):
"""厨师工作线程"""
while self.is_running:
if not self.restaurant.orders.empty():
order = self.restaurant.orders.get()
print(f"👨🍳 {chef_name} 开始处理桌号{order.table_id}的订单")
for dish in order.dishes:
# 模拟烹饪时间
time.sleep(dish.prep_time / 5) # 加速演示
print(f"✅ {chef_name} 完成了: {dish.name} -> 桌号{order.table_id}")
print(f"✨ {chef_name} 完成桌号{order.table_id}的全部菜品")
order.status = 'completed'
# 通知服务员上菜
self._serve_dish(order.table_id)
time.sleep(0.5)
def _serve_dish(self, table_id):
"""上菜"""
print(f"👩💼 服务员: 桌号{table_id},您的菜已上齐!")
# 模拟餐厅运营
def restaurant_simulation():
import threading
restaurant = Restaurant("美味轩")
restaurant.display_menu()
# 启动厨房
kitchen_thread = threading.Thread(target=restaurant.kitchen.start_cooking)
kitchen_thread.start()
# 模拟客人点餐
print("\n🏪 模拟客人陆续到来...")
mock_orders = [
(1, ['宫保鸡丁', '米饭']),
(2, ['红烧肉', '清蒸鲈鱼', '米饭']),
(3, ['麻婆豆腐', '蒜蓉空心菜', '米饭']),
(1, ['酸辣汤']),
(4, ['宫保鸡丁', '红烧肉', '米饭', '米饭'])
]
for table_id, dishes in mock_orders:
time.sleep(2) # 模拟客人间隔到达
print(f"\n👥 客人入座桌号{table_id}")
restaurant.take_order(table_id, dishes)
# 等待所有订单完成
time.sleep(20)
restaurant.kitchen.is_running = False
print("\n🎉 今日营业结束!")
restaurant_simulation()
交通信号灯模拟
import time
import threading
from enum import Enum
from datetime import datetime
class TrafficLightState(Enum):
RED = "🔴"
YELLOW = "🟡"
GREEN = "🟢"
class TrafficLight:
def __init__(self, intersection_id, green_duration=10, yellow_duration=3, red_duration=10):
self.intersection_id = intersection_id
self.green_duration = green_duration
self.yellow_duration = yellow_duration
self.red_duration = red_duration
self.state = TrafficLightState.RED
self.cycles = 0
def run_cycle(self):
"""运行一个信号灯周期"""
while True:
# 绿灯
self.state = TrafficLightState.GREEN
self._display_state()
time.sleep(self.green_duration)
# 黄灯
self.state = TrafficLightState.YELLOW
self._display_state()
time.sleep(self.yellow_duration)
# 红灯
self.state = TrafficLightState.RED
self._display_state()
time.sleep(self.red_duration)
self.cycles += 1
if self.cycles >= 3: # 运行3个周期后停止
break
def _display_state(self):
"""显示信号灯状态"""
now = datetime.now().strftime("%H:%M:%S")
print(f"[{now}] 路口-{self.intersection_id}: {self.state.value} {self.state.name}")
class IntersectionController:
def __init__(self):
self.lights = {
'A': TrafficLight('A', green_duration=8, yellow_duration=2),
'B': TrafficLight('B', green_duration=8, yellow_duration=2),
}
self.sensors = {'N': False, 'S': False, 'E': False, 'W': False}
def simulate_traffic(self):
"""模拟车辆通行"""
import random
vehicles = ['🚗', '🚕', '🚙', '🚌', '🚐', '🏎️']
for light_id in ['A', 'B']:
light = self.lights[light_id]
if light.state == TrafficLightState.GREEN:
# 模拟车辆通过
cars_passing = random.randint(1, 5)
for _ in range(cars_passing):
vehicle = random.choice(vehicles)
print(f" {vehicle} 通过路口-{light_id}")
time.sleep(0.3)
def detect_emergency(self):
"""检测紧急车辆"""
import random
if random.random() < 0.1: # 10%概率出现紧急车辆
print("🚑 紧急车辆接近!")
# 切换所有灯为绿灯
for light in self.lights.values():
light.state = TrafficLightState.GREEN
print("🔴🟢 所有路口变为绿灯让行")
time.sleep(3) # 让行一段时间
def run(self):
"""运行交通控制系统"""
print("🚦 智能交通控制系统启动")
# 启动两个路口的信号灯
threads = []
for light_id, light in self.lights.items():
t = threading.Thread(target=light.run_cycle)
threads.append(t)
t.start()
# 主循环模拟交通
for _ in range(5):
time.sleep(3)
self.simulate_traffic()
self.detect_emergency()
print("\n🚦 交通控制系统结束")
# 模拟交通场景
def traffic_simulation():
controller = IntersectionController()
controller.run()
traffic_simulation()
智能家居系统模拟
import time
import random
from threading import Thread, Event
from datetime import datetime
class SmartDevice:
def __init__(self, name, device_type):
self.name = name
self.type = device_type
self.status = 'off'
self.auto_mode = False
def turn_on(self):
self.status = 'on'
print(f"✅ {self.name} 已开启")
def turn_off(self):
self.status = 'off'
print(f"❌ {self.name} 已关闭")
class SmartHome:
def __init__(self):
self.devices = {}
self.sensors = {}
self.rules = []
def add_device(self, name, device_type):
self.devices[name] = SmartDevice(name, device_type)
def add_sensor(self, name, sensor_type):
self.sensors[name] = {
'type': sensor_type,
'value': 0,
'unit': self._get_sensor_unit(sensor_type)
}
def _get_sensor_unit(self, sensor_type):
units = {
'temperature': '°C',
'humidity': '%',
'light': 'lux',
'motion': None,
'smoke': 'ppm'
}
return units.get(sensor_type)
def add_automation_rule(self, sensor, condition, value, action_device, action):
"""添加自动化规则"""
self.rules.append({
'sensor': sensor,
'condition': condition,
'value': value,
'device': action_device,
'action': action
})
def update_sensor(self, sensor_name, value):
"""更新传感器数值"""
if sensor_name in self.sensors:
self.sensors[sensor_name]['value'] = value
self._check_rules(sensor_name)
def _check_rules(self, sensor_name):
"""检查自动化规则"""
sensor_value = self.sensors[sensor_name]['value']
for rule in self.rules:
if rule['sensor'] == sensor_name:
condition_met = False
if rule['condition'] == '>':
condition_met = sensor_value > rule['value']
elif rule['condition'] == '<':
condition_met = sensor_value < rule['value']
elif rule['condition'] == '==':
condition_met = sensor_value == rule['value']
if condition_met and sensor_name in self.sensors:
device = self.devices.get(rule['device'])
if device:
if rule['action'] == 'on':
device.turn_on()
elif rule['action'] == 'off':
device.turn_off()
def voice_command(self, command):
"""模拟语音控制"""
import re
commands = {
'开灯': ('turn_on', 'light'),
'关灯': ('turn_off', 'light'),
'开空调': ('turn_on', 'air_conditioner'),
'关空调': ('turn_off', 'air_conditioner'),
'开电视': ('turn_on', 'tv')
}
for keyword, (action, device_type) in commands.items():
if keyword in command:
for name, device in self.devices.items():
if device.type == device_type:
if action == 'turn_on':
device.turn_on()
else:
device.turn_off()
return
print("🤔 无法识别指令")
def display_status(self):
"""显示家居状态"""
print("\n🏠 智能家居状态")
print("=" * 40)
for name, device in self.devices.items():
status_icon = "✅" if device.status == 'on' else "❌"
print(f" {status_icon} {name}: {device.status}")
for name, sensor in self.sensors.items():
unit = sensor['unit'] or ''
print(f" 📊 {name}: {sensor['value']}{unit}")
# 模拟智能家居场景
def smart_home_simulation():
home = SmartHome()
# 添加设备
home.add_device("客厅灯", "light")
home.add_device("卧室灯", "light")
home.add_device("客厅空调", "air_conditioner")
home.add_device("电视", "tv")
# 添加传感器
home.add_sensor("温度", "temperature")
home.add_sensor("湿度", "humidity")
home.add_sensor("烟雾", "smoke")
home.add_sensor("人体红外", "motion")
# 添加自动化规则
home.add_automation_rule("温度", ">", 30, "客厅空调", "on") # 温度>30开空调
home.add_automation_rule("烟雾", ">", 100, "客厅灯", "on") # 烟雾>100开灯
home.add_automation_rule("人体红外", "==", 1, "卧室灯", "on") # 有人开灯
print("🏠 智能家居系统启动")
# 模拟日常场景
scenarios = [
("早晨", {"温度": 25, "湿度": 60, "烟雾": 0, "人体红外": 1}),
("中午", {"温度": 35, "湿度": 45, "烟雾": 0, "人体红外": 0}),
("傍晚", {"温度": 28, "湿度": 55, "烟雾": 50, "人体红外": 1}),
("火灾报警", {"温度": 50, "湿度": 30, "烟雾": 200, "人体红外": 0}),
]
for scenario_name, sensor_values in scenarios:
print(f"\n📅 [{scenario_name}]")
print("-" * 40)
for sensor_name, value in sensor_values.items():
home.update_sensor(sensor_name, value)
home.display_status()
# 模拟语音控制
if scenario_name == "傍晚":
print("\n🎤 语音指令测试")
home.voice_command("开电视")
time.sleep(2)
smart_home_simulation()
这些Python案例模拟了多个真实场景:
特点:
- 实际业务逻辑 - 包含完整的业务规则和流程
- 随机事件 - 模拟真实世界的随机性
- 时间流逝 - 使用
time模块模拟时间推移 - 用户交互 - 支持输入输出模拟
- 错误处理 - 包含异常情况和边界条件
- 状态管理 - 跟踪系统状态变化
- 并发处理 - 使用多线程模拟并行操作
应用场景:
- 测试自动化系统
- 演示产品功能
- 学习编程逻辑
- 教学演示
这些案例可以直接运行,也可以根据实际需求进行扩展和修改。