编辑代码

# 第3章/calculateEleccharge.py
# 阶梯电价计算电费

unitPrice = 0.56   # 基础电价
eleCharge = 0      # 每月应缴电费

# 输入有效的月份
while True:
    try:
        month = int(input("请选择当前的月份(1-12):"))
        if 1 <= month <= 12:
            break
        print("输入无效,请输入1-12之间的数字")
    except ValueError:
        print("输入无效,请输入数字")

# 输入有效的度数
while True:
    try:
        sumDegrees = float(input("请输入您当月所使用的用电度数:"))
        if sumDegrees >= 0:
            break
        print("度数不能为负数")
    except ValueError:
        print("输入无效,请输入数字")

# 判断季节并计算电费
if month in [1, 2, 3, 4, 11, 12]:  # 非夏季标准
    if sumDegrees <= 200:
        eleCharge = unitPrice * sumDegrees
    elif 200 < sumDegrees <= 400:
        d1 = 200 * unitPrice
        d2 = (sumDegrees - 200) * (unitPrice + 0.08)
        eleCharge = d1 + d2
    else:
        d1 = 200 * unitPrice
        d2 = 200 * (unitPrice + 0.08)
        d3 = (sumDegrees - 400) * (unitPrice + 0.5)
        eleCharge = d1 + d2 + d3
else:  # 夏季标准
    if sumDegrees <= 200:
        eleCharge = unitPrice * sumDegrees
    elif 200 < sumDegrees <= 500:
        d1 = 200 * unitPrice
        d2 = (sumDegrees - 200) * (unitPrice + 0.05)
        eleCharge = d1 + d2
    else:
        d1 = 200 * unitPrice
        d2 = 300 * (unitPrice + 0.05)
        d3 = (sumDegrees - 500) * (unitPrice + 0.3)
        eleCharge = d1 + d2 + d3

# 输出结果
print(f"您{month}月所使用电量的电费为{eleCharge:.2f}元")