[英]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. 我希望它在玩家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!"
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. 您可以使用
break
提前退出while
循环,也可以在要求玩家2选择标志之前测试剩余的标志数量。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.