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

Python房间漫游程序输入无效方向触发KeyError问题求助

问题分析

你的代码触发KeyError的原因很明确:你在还没判断输入是否有效的时候,就直接用rooms[current_room][user_move]去访问字典键了。如果输入的方向不在当前房间的可选方向里,字典找不到这个键就会抛出KeyError。而且后面的判断逻辑if user_move in current_room完全无效——因为这时候current_room已经被赋值成房间名称的字符串了(比如'Bedroom'),你拿方向字符串去判断是否在房间名称里,逻辑完全错了。

修正后的代码
rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
}
current_room = 'Great Hall'

user_move = ''
directions = ['North', 'South', 'East', 'West']

while user_move != 'exit':
    print("You are in the", current_room)
    user_move = input("Choose a direction ").strip()  # 处理输入前后空格
    
    # 先处理退出指令
    if user_move == 'exit':
        break
    
    # 检查输入的方向是否在当前房间的有效方向中
    if user_move in rooms[current_room]:
        current_room = rooms[current_room][user_move]
        print(f"Moved to {current_room}!")
    else:
        print("Invalid move. Try again")
关键改动说明
  • 判断逻辑提前:先检查输入的方向是否存在于rooms[current_room]的键中(也就是当前房间能去的方向),确认有效后再更新current_room,避免直接访问不存在的字典键触发KeyError。
  • 优先处理退出指令:输入exit时直接跳出循环,不用再执行后续判断。
  • 增加输入格式化:.strip()可以防止用户不小心输入前后空格导致判断失败(比如输入' South ')。
  • 修正判断条件:把错误的user_move in current_room改成user_move in rooms[current_room],正确检查方向是否在当前房间的可选方向字典里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:25:32