Python:在继续之前完成对列表的迭代检查?

Python: complete an iteration check on a list before moving on?

所以我有这个来获取用户的输入(刚学会 Python,使用 2.7 因为有人告诉我):

def get_move_order():
    global move_order
    move_order=[q for q in raw_input("Enter your move order: ")]
    print "Checking the validity of your move..."
    check_correct_moves_only()

我有这个来确保它只有移动列表中的字母:

def check_correct_moves_only():
    moves = ['A','D','S','C','H']
    if all(move_order) in moves:
        return start()
    else:
        print "That's not a proper move!"
        return get_move_order()

问题是,出于某种原因,这并没有真正起作用。我最初是这样的:

def check_correct_moves_only():
    moves = ['A','D','S','C','H']
        for q in move_order:
            if q not in moves:
                print "That's not a proper move!"
                return get_move_order()
            else:
                return start()

但这将 return 输入像 AAAAAAR 这样的东西六次是正确的(在这种情况下,通过打印 "Player 1 ready!" 六次和 "That's not a proper move!" 一次。我希望它检查在继续我在 start() 中的其他检查之前,所有七个(想想回合制游戏,但每个玩家一次给出七个命令)都是这个错误,但我无法获得 work/maybe 的所有功能我用错了吗?我也试过用 any 但是没用。

我会向您提出以下建议:

def get_move_order():  # Asks for a move order until a valid list of moves was entered
    while True:
        move_order = [q for q in raw_input("Enter your move order: ")]

        print "Checking the validity of your move..."
        if check_correct_moves_only(move_order):
            break  # breaks out of the while loop
        else:
            print "That's not a proper move!"
    # valid move has been entered. Start the game.
    start(move_order)

def check_correct_moves_only(move_order):
    moves = ['A', 'D', 'S', 'C', 'H']
    for q in move_order:
        if q not in moves:
            return False
    return True

你用递归的方式写了check_correct_moves_only,这对你的问题来说是不可取的。您还应该仅在真正需要时才使用 global 变量。在大多数情况下,使用参数更具可读性。如果您需要在单独调用的不同方法中使用一些信息,您也可以写一个 class 来代替。

def check_correct_moves_only():
    moves = ['A','D','S','C','H']
    for char in move_order:
        # if any of the moves are invalid it returns false
        if char not in moves or len(move_order)<7: # i understand the move must have 7 letters?
            print ("That's not a proper move!")
            return False
        #if all moves are correct it returns true
    return True

def get_move_order():
    global move_order
    # converted input to capitals because your moves list is in caps
    move_order=[q for q in raw_input("Enter your move order: ")].upper()
    print ("Checking the validity of your move...")
    # repeats process if function returns false
    if check_correct_moves_only() == False:  get_move_order()
    # calls start function if function returns true
    else:  start()

这不是一种非常 Pythonic 的方法,您甚至不应该使用多个函数,但它有效并且很容易理解。