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。我确信我快到了,但是在这一点上我想弄清楚它。谢谢!
1条答案
按热度按时间332nm8kg1#
您需要在移动房间 * 之前 * 验证所选方向是否有效。
您的代码是在检查方向是否有效之前移动房间。