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

时间:2015-06-23 16:37:20

标签: python list iterable

所以我有这个来获取用户的输入(只是学习了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()

但是这将返回AAAAAAR之类的输入正确六次(在这种情况下,通过打印"播放器1准备就绪!"六次和"这不是正确的移动!"一次。我希望它在检查start()中的其他检查之前检查所有七个(想想基于回合的游戏,但每个玩家一次给出七个命令)这个错误,但是我无法使用所有功能/也许我使用它错了?我尝试使用任何功能但是没有用。

2 个答案:

答案 0 :(得分:1)

我建议你:

check_correct_moves_only

您以递归方式编写global,这对您的问题不可取。您也应该仅在真正需要时使用class变量。在大多数情况下,使用参数更具可读性。如果您需要使用分别调用的不同方法中的某些信息,您也可以编写cleanData

答案 1 :(得分:0)

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的方式,你甚至不应该使用多个函数,但它的工作原理很容易理解。