2014-09-22 7 views
0

루프가 조건을 충족하고 다른 기능으로 넘어갈 때 루프가 깨지지 않는 이유는 무엇입니까? 나는 진실한 루프를하고 각각의 if 문을 깨뜨림으로써 그것을 고쳤지만, 이런 식으로 무엇이 잘못되었는지 알고 싶습니다.조건이 충족 될 때 파이썬 while 루프가 깨지지 않는 경우

데프 main_entrance() :이 침입하지 않습니다 물론

print "\n\tYou are in the main entrance. It is a large room with" 
print "\ttwo doors, one to the left and one to the right. There" 
print "\tis also a large windy stair case leading up to a second floor." 
print "\n\tWhat are you going to do?\n" 
print "\t #1 take the door on the left?" 
print "\t #2 take the door on the right?" 
print "\t #3 take the stairs to the second floor?" 

choice = 0 

#This seems to be the part that isn't working as I would expect it to. 
# I have fixed it and have commented the fix out so that I can understand 
# why this way isn't working. 

#while True: 

while (choice != 1) or (choice != 2) or (choice != 3): 


    try: 
     choice = int (raw_input ('> ')) 
     if (choice == 1): 
      door_one_dinning_room() 
      #break (should not need this break if choice is == 1, 2, 3) 

     elif (choice == 2): 
      door_two_study() 
      #break 

     elif (choice == 3): 
      stairs_to_landing() 
      #there isn't anything in this function 
      #but rather than breaking out from the program once it is 
      # called, but somehow this while loop is still running. 

      #break 

     else: 
      print "You must pick one!" 

    except: 
     print "Please pick a number from 1-3" 
     continue 
+1

[이] (http://stackoverflow.com/a/25860636/1189040)이 아니라 더 나은 대안 – Himal

답변

9

, 당신의 상태가

(choice != 1) or (choice != 2) or (choice != 3) 

는 잠시 생각해 거짓 없다, 선택의 선택은 할 수 없습니다 이 표현식은 거짓이다.

선택 = 1

False or True or True --> True 

선택 = 2

True or False or True --> True 

선택 = 당신은 북동

3

True or True or False --> True 

솔루션 에드

while choice not in [1,2,3] 
+0

수 있습니다 설명하고 간결한 솔루션! 나는이 대답을 많이 좋아한다! –

+0

젠장, 왜 그걸 알아 차리지 못했지! 이제 바보 같아. LOL .. 네, 내 논리가 끝났어. 프로그래밍에 익숙하지 않았습니다. 모든 것이 완벽하게 이해됩니다! –

+0

[1,2,3] 대신 {1,2,3}을 사용하십시오. 집합 조회는 목록 조회보다 효율적입니다. 사용중인 파이썬의 버전에 따라 리터럴 세트 (또는리스트)는 런타임이 아닌 컴파일 타임에 생성 될 수 있습니다. 이는 런타임을 강조 할 것입니다. – chepner

5
while (choice != 1) or (choice != 2) or (choice != 3): 

이 조건이 항상 사실 더 좋은 조건 함께

(choice != 1) and (choice != 2) and (choice != 3) 

and 또는합니다. choice 변수가 1이면 choice!=1이 거짓이지만 choice!=2이 참이므로 전체 조건이 참입니다. 그것이 바로 or의 의미입니다. 더 간결

while (choice != 1) and (choice != 2) and (choice != 3): 

또는 :

당신은 넣을 수

while choice not in (1,2,3): 
+0

위와 같음 .. 대단히 감사합니다 ... –

+0

'(1,2,3)'대신'{1,2,3}'를 사용하십시오. 세트 룩업은 튜플 룩업보다 더 효율적입니다. 사용중인 Python의 버전에 따라 리터럴 집합 (또는 튜플)을 런타임이 아닌 컴파일 타임에 만들 수 있습니다. 이는 런타임을 강조 할 것입니다. – chepner

관련 문제