2014-04-06 2 views
0

플레이어 1이 마지막 플래그를 사용하면 끝내기를 원하지만 플레이어 2에게 요청하면 종료되지 않습니다.파이썬에서 while 루프를 종료하는 방법?

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

코드의 마지막 부분에 플래그에 대한 검사가 다른 문에 야해 – Craicerjack

답변

0

일찍 break를 사용하여 while 루프를 종료하거나 플래그를 선택하는 플레이어 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 
관련 문제