Python在房间之间移动键错误消息

3phpmpom  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(103)
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。我确信我快到了,但是在这一点上我想弄清楚它。谢谢!

332nm8kg

332nm8kg1#

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

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")

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

相关问题