【问题标题】:While loop inside a function?函数内部的while循环?
【发布时间】:2020-12-03 17:16:00
【问题描述】:

我对编码完全陌生,并且正在使用 Python 开发基于文本的游戏作为学校项目。用户必须通过键入“North”、“East”、“South”或“West”进入房间。如果方向无效,应弹出错误消息,提示用户输入新方向。如果用户输入“退出”,游戏应该结束。

我在这个项目中遇到了一百万个问题,因为我发现我在编码方面很糟糕,但我想弄清楚的是如何让我的程序在出现提示时退出游戏。这是我的代码(它不是完整的代码,只是我目前所拥有的。我试图一步一步解决问题,这就是我卡住的地方):

rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}


def main():
    current_room = 'Great Hall'
    user_input = None

    while user_input != "Quit":
        print('You are in the', current_room + '.')
        user_input = input('Where would you like to go?: ')
        current_room = rooms[current_room][user_input]
    else:
        print('Thanks for playing!')


main()

当我运行程序时,我收到以下错误消息: Error Message

如果有人能指出我需要解决的正确方向,我将不胜感激!

【问题讨论】:

  • 您的房间变量不包含退出信息。 rooms[current_room]['Quit']
  • 您的while 循环一直运行,直到用户的输入为Quit。但是,如果是Quit,代码将尝试访问不存在的rooms[current_room]['Quit']。你应该只有一个while True 循环,然后是break,如果用户的输入是Quit,并且只有你检查之后,你才会运行current_room = rooms[current_room][user_input]。但您可能想检查用户输入是否是rooms 中的有效键:stackoverflow.com/questions/23294658/…

标签: python function loops


【解决方案1】:

所以当您的用户输入"Quit" 时,您继续尝试在rooms 中找到它。您应该将退出条件移到输入之后,而不是成为while 条件的一部分:

rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}


def main():
    current_room = 'Great Hall'

    while True:
        print('You are in the', current_room + '.')
        user_input = input('Where would you like to go?: ')
        if user_input == "Quit":
            break
        current_room = rooms[current_room][user_input]
    print('Thanks for playing!')

main()

【讨论】:

    【解决方案2】:

    尝试将其放在 if 语句中?您的错误正在发生,因为它试图在循环回到 while 语句之前找到要移动的正确房间。使用 if 立即强制它首先确定退出。

    rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }
    
    
    def main():
        current_room = 'Great Hall'
        user_input = None
    
        while user_input != "Quit":
            print('You are in the', current_room + '.')
            user_input = input('Where would you like to go?: ')
            
            if user_input == "Quit":
                print('Thanks for playing!')
            else:
                current_room = rooms[current_room][user_input]
        
    
    main()
    

    【讨论】:

      【解决方案3】:

      您可以使用海象运算符以获得更简单的代码:

      rooms = {
          'Great Hall': {'South': 'Bedroom'},
          'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
          'Cellar': {'West': 'Bedroom'}
      }
      
      def main():
          current_room = 'Great Hall'
      
          while user_input:=input('Where would you like to go?: ') != 'Quit':
              print('You are in the ' + current_room + '.')
              current_room = rooms[current_room][user_input]
          print('Thanks for playing!')
      
      main()
      

      【讨论】:

        【解决方案4】:

        错误是 Quit 键不在房间字典中。我有一个有效的代码版本:

        rooms = {
            'Great Hall': {'South': 'Bedroom'},
            'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
            'Cellar': {'West': 'Bedroom'}
        }
        
        def main():
            current_room = 'Great Hall'
        
            while True:
                print('You are in the', current_room + '.')
                user_input = input('Where would you like to go?: ')
                if user_input == "Quit":
                    break
            if user_input in rooms[current_room]:
                current_room = rooms[current_room][user_input]
            print('Thanks for playing!')
        main()
        

        【讨论】:

          【解决方案5】:

          这是对代码的改进,以避免dict中的ErrorKey:

          rooms = {
          'Great Hall': {'South': 'Bedroom'},
          'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
          'Cellar': {'West': 'Bedroom'}
          }
          
          
          def main():
              current_room = 'Great Hall'
          
          while True:
              print('You are in the', current_room + '.')
              user_input = input('Where would you like to go?: ')
              if user_input == "Quit":
                  break
              possible_directions = rooms[current_room].keys()
              if user_input not in possible_directions:
                  print()
                  print('You can not go:', user_input)
                  print('Try instead', )
                  print(possible_directions)
                  print()
                  continue
              current_room = rooms[current_room][user_input]
          print('Thanks for playing!')
          
          main()
          

          需要注意的是程序启动了一个无限循环。因此,如果您像我一样在 Jupyter Notebook 中运行它,并且在键入“退出”之前再次运行单元格,Jupyter 仍将同时执行前一个进程和新进程。

          【讨论】:

            猜你喜欢
            • 2020-06-16
            • 2013-12-12
            • 1970-01-01
            • 2015-05-10
            • 2021-02-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多