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

如何在while循环条件中正确使用字典键值实现年龄区间判断?

用字典实现电影票价年龄区间校验的正确写法

想要编写一个程序,获取用户年龄后告知其对应的电影票价。原本用少量年龄区间实现很简单,但为了练习使用字典(便于后续仅修改字典即可调整区间规则),编写了如下代码,但在while循环的条件判断中调用字典键值时出现问题,尝试过直接调用键值、结合for循环等方式仍无法正确实现,希望了解如何在条件判断中正确使用字典的键来完成年龄区间校验。

错误代码示例:

name = input(f"Hello, what's your name? ")
age = int(input(f"And what is your age, {name}? "))

prices = {3: 'free', 11: 10, 12: 15}

# print(prices[0])

while True:
    if age < prices{0}
        print(f"Your ticket is free!")
    elif prices{0} <= age < prices{1}:
        print(f"The price of your ticket is {int{} ")
    else:
        print(f"The price of your ticket is")

问题拆解

  1. 字典访问语法错误:你用prices{0}这种错误写法访问字典,正确的字典取值是prices[key],而且你的字典键是3、11、12,不存在0、1这类索引键,直接用数字索引会触发KeyError。
  2. 区间逻辑与字典结构不匹配:当前字典的键值对没有明确对应区间规则,比如3: 'free'应该对应“年龄小于3免费”,但你试图用索引来区分区间,这不符合字典的使用逻辑。
  3. 其他语法问题:while循环无终止条件会无限循环,字符串格式化存在语法错误({int{} )。

正确实现方案

我们可以把字典设计为「区间上限: 对应票价」的结构,先对区间上限排序,再遍历匹配年龄对应的区间,这样后续修改规则只需调整字典,不用改动逻辑代码:

name = input(f"Hello, what's your name? ")
age = int(input(f"And what is your age, {name}? "))

# 键是区间上限,值是对应票价;规则:年龄 < 键 时适用该票价
# 用float('inf')(无穷大)覆盖所有超出设定区间的年龄
price_rules = {
    3: 'free',
    12: 10,
    float('inf'): 15
}

# 对区间上限从小到大排序,保证判断顺序正确
sorted_limits = sorted(price_rules.keys())

# 遍历排序后的区间,匹配年龄对应的票价
for limit in sorted_limits:
    if age < limit:
        ticket_price = price_rules[limit]
        if ticket_price == 'free':
            print(f"Your ticket is free!")
        else:
            print(f"The price of your ticket is ${ticket_price}")
        break

关键说明

  • 字典price_rules的键代表区间的上限,比如3对应“年龄<3”,12对应“3≤年龄<12”,float('inf')对应“年龄≥12”。
  • 通过sorted()对区间上限排序,确保从低到高判断,避免逻辑混乱。
  • 后续调整规则只需修改字典:比如新增18:20表示18岁及以上票价20,直接添加到price_rules即可,无需修改循环逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:10:27