"""3f 课后练习答案：流程控制与实训。"""

print("=" * 64)
print("第一部分：条件分支与边界")


def grade(score):
    """根据分数返回优秀、良好、中等或差。"""
    if score >= 85:
        return "优秀"
    elif score >= 75:
        return "良好"
    elif score >= 60:
        return "中等"
    return "差"


for score in [59, 60, 74, 75, 84, 85]:
    print(score, "->", grade(score))

print("\n第二部分：条件嵌套")


def days_in_month(year, month):
    """返回指定年月的天数；month 不合法时返回提示文本。"""
    if month in [1, 3, 5, 7, 8, 10, 12]:
        return 31
    elif month in [4, 6, 9, 11]:
        return 30
    elif month == 2:
        is_leap = year % 400 == 0 or (
            year % 4 == 0 and year % 100 != 0
        )
        if is_leap:
            return 29
        return 28
    return "月份必须在 1 到 12 之间"


print("2024 年 2 月：", days_in_month(2024, 2))
print("2023 年 2 月：", days_in_month(2023, 2))

print("\n第三部分：while 循环")


def sum_to_n(n):
    """返回 1 到 n 的累加和；n 为正整数。"""
    current = 1
    total = 0
    while current <= n:
        total += current
        current += 1
    return total


print("1 到 10 的和：", sum_to_n(10))

print("\n第四部分：for 与循环嵌套")


def draw_board(size):
    """输出 size 行、size 列的棋盘；相邻格交替为 + 和 -。"""
    for row in range(size):
        for col in range(size):
            if (row + col) % 2 == 0:
                print("+", end=" ")
            else:
                print("-", end=" ")
        print()


draw_board(4)

print("\n第五部分：物流费用")


def shipping_fee(region_code, weight_kg):
    """返回物流费用；地区只允许 01、02、03，重量必须大于 0。"""
    if weight_kg <= 0:
        return "重量必须大于 0"

    if region_code == "01":
        first_price, extra_price = 13, 3
    elif region_code == "02":
        first_price, extra_price = 12, 2
    elif region_code == "03":
        first_price, extra_price = 14, 4
    else:
        return "地区编号只能是 01、02 或 03"

    if weight_kg <= 2:
        return first_price

    extra_kg = int(weight_kg - 2)
    if weight_kg - 2 > extra_kg:
        extra_kg += 1
    return first_price + extra_kg * extra_price


print("华东 1.5 kg：", shipping_fee("01", 1.5))
print("华北 3.2 kg：", shipping_fee("03", 3.2))

print("\n第六部分：三次机会登录")


def login_check(attempts):
    """遍历最多 3 次尝试，成功立即返回成功消息。"""
    expected_user = "admin"
    expected_password = "python"
    attempt_no = 0

    for user, password in attempts:
        attempt_no += 1
        if user == expected_user and password == expected_password:
            return f"第 {attempt_no} 次：登录成功"
    return "输入错误次数过多，请稍后再试"


attempts = [("admin", "123"), ("guest", "python"), ("admin", "python")]
print(login_check(attempts))

print("\n第七部分：自检答案")

# while 循环的初值是开始前的变量值；条件决定是否继续循环；
# 更新语句必须改变参与条件的变量，避免无限循环。
# break 立即结束整个循环，例如找到目标后停止查找；
# continue 跳过本轮剩余代码，例如跳过不合格数据。
