You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python入门学习者咨询露营地明细收据程序的代码简化方案

代码优化方案

核心简化思路

  • 提取重复的输入校验逻辑为通用函数,消除重复代码
  • 删除无意义的外层while True循环(原代码中循环体只执行一次就break,完全没有存在必要)
  • 优化零除错误处理:在输入露营人数环节直接限制输入≥1的正整数,比后续报错赋值0的逻辑更符合实际使用场景
  • 输出统一使用f-string格式化,语法更简洁易读,同时实现你需要的输出内容染色效果

优化后完整代码

# 露营地明细账单生成程序
# 常量定义
ELECTRICITY = 10.00  # 一次性电费

# 终端颜色定义
class Colors:
    ERROR = "\033[91m"
    SUCCESS = "\033[92m"
    END = "\033[0m"


def get_valid_input(prompt: str, input_type: type, error_msg: str) -> any:
    """通用输入校验函数"""
    while True:
        try:
            value = input_type(input(prompt))
            # 针对露营人数特殊校验,不能小于1
            if input_type == int and "露营人数" in prompt and value < 1:
                print(f"{Colors.ERROR}错误:露营人数不能小于1{Colors.END}")
                continue
            return value
        except ValueError:
            print(f"{Colors.ERROR}{error_msg}{Colors.END}")


# 输入采集
nightly_rate = get_valid_input("请输入每晚基础费率:$", float, "错误:请输入有效金额")
number_of_nights = get_valid_input("请输入入住晚数:", int, "错误:请输入有效数字")
campers = get_valid_input("请输入露营人数:", int, "错误:请输入有效数字")

# 费用计算
campsite = nightly_rate * number_of_nights
tax = (ELECTRICITY + campsite) * 0.07  # 电费和营地费都按7%计税,原写法合并简化
ranger = (campsite + ELECTRICITY + tax) * 0.15  # 护林员小费
total = campsite + ELECTRICITY + tax + ranger
total_per = total / campers  # 已经提前限制人数≥1,不会触发零除错误

# 明细输出
print(f"每晚费率----------------------- {nightly_rate}")
print(f"入住晚数----------------------- {number_of_nights}")
print(f"露营人数----------------------- {campers}")
print()
print(f"营地费------------------------- {Colors.SUCCESS}${campsite:.2f}{Colors.END}")
print(f"电费--------------------------- {Colors.SUCCESS}${ELECTRICITY:.2f}{Colors.END}")
print(f"税费--------------------------- {Colors.SUCCESS}${tax:.2f}{Colors.END}")
print(f"护林员小费--------------------- {Colors.SUCCESS}${ranger:.2f}{Colors.END}")
print(f"总费用------------------------- {Colors.SUCCESS}${total:.2f}{Colors.END}")
print()
print(f"人均费用----------------------- {Colors.SUCCESS}${total_per:.2f}{Colors.END}")

额外说明

你之前要的输出染色已经实现,所有金额部分都会显示为绿色,报错信息保持红色,不需要变色的内容不会加颜色码。

内容的提问来源于stack exchange,提问作者Phantom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:09:03