python - Python 中永无休止的验证检查

标签 python validation

正在用 Python 开发战舰游戏。我的功能是检查用户的“猜测”输入,从而导致无限的验证循环。我想要猜测 10x10 网格上“a10”的格式。我为帮助验证而构建的验证函数如下:

  def validate_guess(self,guess):
        while True:
            if (len(guess)) in range(2, 4):
                if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
                    print("Sorry the Grid is a 10x10 square you must enter a valid position.  Try again...")
                    continue

                else:
                    return guess

            else:
                if len(guess) < 2 or len(guess) > 3:
                    print("Oops!  That's too not the right amount of characters. Please try again...")
                    continue

如果用户猜测了一个不正确的值——它确实发现了它——但错误将返回一个带有打印错误语句的永无止境的循环。

这是我的游戏中使用验证函数的部分:

while True:
        print("\n")
        # get guess from player one in coordinate form (example: a10)
        guess = input("{}'s turn to guess: ".format(player1.player))
        # strip characters from the guess input
        guess = guess.strip()
        # validate the guess
        guess = self.validate_guess(guess)
        # append the guess to a list for player 1
        player1.guesses.append(guess)
        # break down the coordinates into x and y variables
        x, y = ship1.split_guess(guess)
        # increment guesses
        guesses += 1
        # loop to assess whether, hit, miss or a won game
        if any(guess in ship for ship in grid2.play_two_board):
            print("HIT")
            grid2.print_guess_board(x, y, "h")
            for ship in grid2.play_two_board:
                try:
                    ship.remove(guess)
                    print(len(Board.play_two_board))
                    self.check_if_sunk(ship)
                    win = self.play_one_win_check(player1.player)
                    if win == 1:
                        print ("GAVE OVER!")
                        break
                except ValueError:
                    pass
        else:
            print("Miss!")
            grid2.print_guess_board(x, y, "m")

不确定是否是因为我有两个 While 语句?只是真的被困在这里,希望得到任何指导。谢谢。

********************************8 编辑 --changed 函数以包含猜测,但实际上没有从输入语句中传递该值,但仍然遇到相同的问题。

  def validate_guess(self):
        guess = input("Please enter a location:")
        while True:
            if len(guess) in range(2, 4):
                if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
                    print("Sorry the Grid is a 10x10 square you must enter a valid position.  Try again...")
                    continue

                else:
                    return guess

            else:
                if len(guess) < 2 or len(guess) > 3:
                    print("Oops!  That's too not the right amount of characters. Please try again...")
                    continue

并像这样调用它:

while True:
        print("\n")
        # get guess from player one in coordinate form (example: a10)
        # guess = input("{}'s turn to guess: ".format(player1.player))
        # strip characters from the guess input
        # guess = guess.strip()
        # validate the guess
        guess = self.validate_guess()

最佳答案

validate_guess中,当用户输入错误值时,您必须在再次检查之前获取新的输入。请参阅here .

要么从函数返回错误代码(True/False?),要么让函数循环直到输入有效。只需在函数的 while 循环底部添加一个用于新输入的命令即可。

关于python - Python 中永无休止的验证检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42794802/

相关文章:

python - PySpark partitionBy、repartition 还是什么都不做?

python - matplotlib 散点图的颜色参数是 `c` ,但是 `color` 也可以;产品。差异。结果

python - 加密——怎么做

python - 在 OSX 10.6 上导入 Python Sybase 模块时出现 undefined symbol

python - ElasticSearch 在索引数据时不尊重自定义映射

php - 使用 PHP 验证 rfc2616 日期字符串

java - 如何在登录 Activity 中验证用户名

html - 如何强制 Visual Studio 2010 刷新其错误列表窗口?

asp.net - 可以让 CompareValidator 接受带逗号的数字吗?

php - Laravel 验证 : exists two column same row