如果用户输入无效的输入(Python),则从头开始重新启动循环

时间:2020-07-16 01:00:36

标签: python while-loop user-input

我最近开始研究战舰计划。我相信我的代码结构有麻烦。在下面的代码段中,我试图提示用户,直到他们输入有效的船坐标为止。当用户输入无效坐标时,循环从头开始重新启动。它按我想要的方式工作。但是,我认为可能有一种更有效的方法来执行此操作,而不是依赖于continue语句。

预先感谢

 # Obtain valid coordinates from user
while True:
    try:
        start_coords = self.convert_input(input("\nEnter the ship's starting coordinates (ex. a1): ").upper())
        end_coords = self.convert_input(input("\nEnter the ship's ending coordinates (ex. a4): ").upper())
    except KeyError:
        print('\nPlease enter valid coordinates.')
    except ValueError:
        print('\nPlease enter valid coordinates')
    else:
        # prevent user from inserting ship in a spot that's already occupied
        if self.board[start_coords[0]][start_coords[1]] == 1:
            print("\nThat spot is already occupied!")
            continue
        # make sure that ship's coordinates are vertical
        if orientation == 'V':
            if start_coords[1] != end_coords[1]:
                print("The ship's coordinates aren't in a vertical direction!")
                continue
            # prevent ship from being placed in occupied area
            count_ones = 0
            for i in range(start_coords[0], end_coords[0] + 1):
                if self.board[i][start_coords[1]] == 1:
                    count_ones += 1
            if count_ones != 0:
                print("That space is occupied!")
                continue

        break

0 个答案:

没有答案