如何在Python中循环这个循环?

时间:2014-04-06 09:23:16

标签: python

如果玩家1拿到最后一个标志,我希望它退出,但会发生的是它询问玩家2并且它不会退出。

while (flags>0):
    print "There are",flags,"flags left."

    print "Next player is 1"
    selection=input("Please enter the number of flags you wish to take: ")
    if (selection<1)or (selection>3):
            print "You may only take 1, 2 or 3 flags."
            selection=input("Please enter the number of flags you wish to take: ")
    else:
            flags=flags-selection
    print "There are",flags,"flags left."

    print "Next player is 2"
    selection=input("Please enter the number of flags you wish to take: ")
    if (selection<1)or (selection>3):
            print "You may only take 1, 2 or 3 flags."
            selection=input("Please enter the number of flags you wish to take: ")
    else:
            flags=flags-selection


    else:
        if (flags<0) or (flags==0):
             print "You are the winner!"

1 个答案:

答案 0 :(得分:0)

您可以使用while提前退出break循环,也可以在要求玩家2选择标记之前测试剩余的标记数。

例如

print "Next player is 1"
selection=input("Please enter the number of flags you wish to take: ")
if (selection<1)or (selection>3):
        print "You may only take 1, 2 or 3 flags."
        selection=input("Please enter the number of flags you wish to take: ")
else:
        flags=flags-selection
print "There are",flags,"flags left."

if flags <= 0:
    print "Player 1 is the winner!"
    break

您可能希望重新构建代码以在玩家之间切换:

player = 1

while True:
    print "Next player is {}".format(player)
    selection = input("Please enter the number of flags you wish to take: ")
    if not 1 <= selection <= 3:
            print "You may only take 1, 2 or 3 flags."
            selection = input("Please enter the number of flags you wish to take: ")
    else:
            flags = flags - selection
    print "There are",flags,"flags left."
    if flags <= 0:
        print "Player {} is the winner!".format(player)
        break

    player = 3 - player  # swap players; 2 becomes 1, 1 becomes 2