简体   繁体   中英

How to exit this while loop in Python?

I want it to exit if Player 1 takes the last flag, but what happens is that it asks player 2 and it won't exit.

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!"

You can exit the while loop early by using break , or you can test for the number of flags left before asking player 2 to pick flags.

For example

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

You may want to restructure your code to alternate between players:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM