在 Python 中重新提示动作

re-prompting moves in Python

我在哪里可以在这段代码中添加一个while循环来请求另一个动作。我真的需要帮助我想不通。我想让它重新提示移动,所以当移动无效时,它会再次要求另一个移动。如果移动有效,它会要求下一步移动?

def valid1(pile1):
    move = False
    pile1 = 3
    if pile1 == 0:
        print 'please choose from pile 2 and 3:'
    elif pile1 == 3:

        move = int(input('please choose the amount you would like:'))
        if move > 0 and move <= 2:
            pile1 = pile1 - move
        else:
            print 'you have entered a invalid move'
        return pile1
    elif pile1 == 2:

        move = int(input('please choose the amount you would like:'))
        if move > 0 and move <= 2:
            pile1 = pile1 - move
        else:
            print 'you have entered a invalid move'
        return pile1
    elif pile1 == 1:

        move = int(input('please choose the amount'))
        if move > 0 and move <= 1:
            pile1 = pile1 - move
        else:
            print 'you have entered a invalid move'
        return pile1
    else:
        print pile2


print valid1(3)

我发现很难准确理解您的代码,所以我不确定要循环哪一位,但我认为如果您使用以下一般原则,您将解决此问题:

 looping = True
 while looping = True :
     move = int(input('please choose the amount you would like:'))
        if move > 0 and move <= 2:
            pile1 = pile1 - move
        else:
            print 'you have entered a invalid move'
        return pile1

在上面的代码中,您将一直循环,因此在您输入一个动作后将继续询问输入提示。如果你想在满足某个条件时跳出循环,那么在你对条件进行编码之后,将 looping = False。在python中,布尔值的首字母必须大写。还有其他方法可以做到这一点,例如使用 break 语句等,但这是我更喜欢使用的方法。正如我所说,我不确定您到底想在代码中循环什么,但是如果您将它全部包含在上面的 'while' 语句中,它应该被修复。希望这对您有所帮助!