Python Move between rooms关键错误消息


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 ")
current_room = rooms[current_room][user_move]
if user_move in current_room:
print(current_room)
else:
print("Invalid move. Try again")

你好,我是一个极端的新手python和我有一个问题,我的if/else语句。当我故意放入无效方向以查看输出时,会得到KeyError。我确信我就快成功了,但此时我已经脑死亡,试图弄清楚它。谢谢!

您需要在移动房间之前验证所选择的方向是否有效

while user_move != 'exit':
print("You are in the", current_room)
user_move = input("Choose a direction ")
# is the move a valid choice?
if user_move in rooms[current_room]:
# yes it is valid, so move there
current_room = rooms[current_room][user_move]
print(current_room)
else:
# no, it was not a valid move
print("Invalid move. Try again")

您的代码在检查方向是否有效之前移动房间。

相关内容

最新更新