目标:掌握条件判断和循环,能编写订单审核与批量处理程序。
一、条件判断(if语句)
1. 基础订单审核
order_amount = float(input("请输入订单金额:"))
if order_amount > 5000:
print("该订单需经理审批")
elif order_amount > 2000:
print("需主管审核")
else:
print("自动通过")
2. 多重条件判断(库存检查)
stock = 15
is_urgent = True
if stock < 10:
print("立即补货!")
elif stock < 20 and is_urgent: # 且关系
print("优先发货")
else:
print("库存充足")
二、循环处理
1. while循环:持续接收订单
total_orders = 0
max_orders = 5
while total_orders < max_orders:
print(f"正在处理第 {total_orders+1} 笔订单")
total_orders += 1
print("今日订单已满")
2. for循环:批量价格调整
prices = [25.5, 30.0, 18.9, 45.0]
# 所有商品涨价10%
new_prices = []
for price in prices:
new_prices.append(price * 1.1)
print("新价格表:", new_prices)
三、综合实战:自动化订单流水线
需求:
- 自动审核订单金额
- 批量处理5个订单
- 统计总销售额
total_income = 0
order_count = 0
while order_count < 5:
amount = float(input(f"请输入第 {order_count+1} 笔订单金额:"))
if amount <= 0:
print("金额无效,跳过")
continue # 跳过当前循环
total_income += amount
order_count += 1
# 审核逻辑
if amount > 3000:
print("⚠️ 大额订单需人工核查")
print(f"总销售额:{total_income:.2f} 元")
四、今日任务清单
- 修改价格调整代码,实现第二件半价
提示:用for i in range(len(prices))遍历索引 - 增加订单金额为负数时的处理(使用
break终止循环) - 实验
continue与break的区别
常见错误排查
- 缩进错误:
→ 确保if/for代码块统一缩进4个空格 - 无限循环:
→ 检查while条件是否会被修改 - 浮点数比较:
→ 避免price == 10.0,改用abs(price - 10.0) < 0.001