2013-08-23 3 views
0

나는 숙제가 있습니다. 다음을 나타내는 사전을 만들어야합니다.상태가 작동하지 않는 동안 Python

북쪽은 정원으로 연결됩니다. 남쪽으로 부엌으로 연결됩니다. 동쪽 식당으로 연결됩니다. 웨스트가 거실로 연결됩니다.

플레이어는 방향을 묻는 메시지를 표시하고 그 방향으로 벗어난 위치로 응답해야합니다. 예를 들어 플레이어가 북쪽으로 을 입력하면 프로그램에서 다음과 같이 응답해야합니다. 북쪽이 정원으로 연결됩니다. 플레이어가 잘못된 방향을 입력하면 프로그램에서 입력 을 무시하고 다른 방향을 물어야합니다. 플레이어 이 종료되면 프로그램이 종료됩니다.

내 문제는 사용자가 "quit"을 입력하면 프로그램이 종료되지 않습니다. 그래서 나는 왜 while 문이 작동하지 않는지 이해하지 못했습니다. 여기 내 코드입니다 : 나는 때문에 당신이 당신의 코드를 들여 쓰기 한 방법으로 확신 할 수 없다

#Create a Dictionary to represent the possible 
#exits from a location in an adventure game 

game = {"north" : "North leads to garden.", 
    "south" : "South leads to the kitchen.", 
    "east" : "East leads to the dining room.", 
    "west" : "West leads to the living room."} 
print "Press quit to exit" 

direction = raw_input("Enter your direction: ") 
while direction != "quit": 
    direction = direction.lower() 

    if direction in game: 
     location = game[direction] 
     direction = direction.lower() 
     print location 


    if direction not in game: 
     direction = raw_input("Enter your direction: ") 
     location = game[direction] 
     direction = direction.lower() 
     print location 

    raw_input("\n\nPress quit to exit") 
+1

"quit"은 언제 입력합니까? –

+4

코드를 들여 쓰기 할 수 있습니까? 우리는 루프 외부에 무엇이 있는지, 루프에 실제로 무엇이 있는지 모릅니다. 명령문과 동일합니다. – Paco

+0

프로그램의 시작 부분에 "quit"을 입력해야합니다. –

답변

1

다른 것들과 마찬가지로, 들여 쓰기가 부족하여 코드에서 수행하려고하는 작업을 완전히 확신 할 수는 없지만 어둠 속에서도 한 발을 감당할 수있는 방법을 얻는 것이 더 쉽습니다. 나쁜 방향을 다룰 방향. 따라서 귀하의 코드는 다음과 같이 될 수 있습니다 :

#Create a Dictionary to represent the possible 
    #exits from a location in an adventure game 

def get_dir(): 
    good_answers = ["north", "south", "east", "west", "quit"] 
    direction = raw_input("Enter your direction: ").lower() 
    while direction not in good_answers: 
     direction = raw_input("Bad direction, try again: ").lower() 
    return direction 

game = {"north" : "North leads to garden.", 
    "south" : "South leads to the kitchen.", 
    "east" : "East leads to the dining room.", 
    "west" : "West leads to the living room."} 

print "Press quit to exit" 
direction = get_dir() 
while direction != "quit": 
    print game[direction] 
    direction = get_dir() 

print "Quitting..." 
3

그러나 나는 문제가 생각 :

raw_input("\n\nPress quit to exit") 

은 다음과 같아야합니다

direction = raw_input("\n\nPress quit to exit") 

그러나 몇 가지 문제가 있습니다. 방향이 종료되지 않은 입력하거나 우리가이 시점에서 종료 입력하면 있도록 사전에 인 코드의이 시점에서

if direction not in game:   
    direction = raw_input("Enter your direction: ") 
    location = game[direction] 
    direction = direction.lower() 
    print location 

우리가 얻을 :

Traceback (most recent call last): 
    File "homework.py", line 21, in <module> 
    location = game[direction] 
KeyError: 'quit' 

우리는 두 가지 방법으로이 문제를 해결할 수 , 우리는 그것을 시도해 볼 수 있고 그 예외를 처리 할 수 ​​있거나 사전의 회원을 다시 확인할 수 있습니다. 예를 들면 : 당신은 당신이 디버깅하는 동안 중요한 정보를 잃어 버리게 모든 예외를 침묵으로 싶어하지 않는

if direction not in game:   
    try: 
     direction = raw_input("Enter your direction: ") 
     location = game[direction] 
     direction = direction.lower() 
     print location 
    except KeyError: 
      pass 

난 단지 except KeyError을 사용했다. 사전에 있는지 확인하는 방법을 알았으므로이 방법을 다시 표시 할 필요가 없습니다. 우리가 함께 넣어 경우

그래서 우리가 얻을 :

#Create a Dictionary to represent the possible 
#exits from a location in an adventure game 

game = {"north" : "North leads to garden.", 
     "south" : "South leads to the kitchen.", 
     "east" : "East leads to the dining room.", 
     "west" : "West leads to the living room." 
} 

direction = raw_input("Enter your direction: ") 

while direction != "quit": 
    direction = direction.lower() 
    if direction in game: 
     location = game[direction] 
     direction = direction.lower() 
     print location 

    if direction not in game:   
     try: 
      direction = raw_input("Enter your direction: ") 
      location = game[direction] 
      direction = direction.lower() 
      print location 
     except KeyError: 
      pass 

    direction = raw_input("\n\nPress quit to exit: ") 

우리는 프로그램이 실행되는 방법을 찾아야한다이 점에 도착하면, 우리는 우리가하는 동안 사용자의 입력을 위해 여러 번 요청하고 있습니다 볼 수 있습니다 동일한 변수를 설정하여 스크립트를 실행합니다. 이제 우리는 필요한 호출을 제거하는 작업을해야합니다. 우리가 try: except 블록을 추가 한 이후 : 우리는 우리 잎 사전에 회원에 대해 이전 확인이 필요하지 않습니다 : 내가 생각하는이 시점에서

#Create a Dictionary to represent the possible 
#exits from a location in an adventure game 

game = {"north" : "North leads to garden.", 
     "south" : "South leads to the kitchen.", 
     "east" : "East leads to the dining room.", 
     "west" : "West leads to the living room." 
}  
# Initialize the direction variable 
direction = "" 
# Keep looping user types in quit 
while direction != "quit": 
     try: 
      # Take the user input at the start of the loop 
      direction = raw_input("Enter your direction Or quit to exit: ") 
      # Get the location string if it exists 
      location = game[direction] 
      # Make the string lower case 
      direction = direction.lower() 
      # Display location message 
      print location 
     # If this KeyError is raised user has entered a location not in the 
     # dictionary 
     except KeyError: 
      # We can do nothing because we are just going to get new user input 
      # next time the loop runs! 
      pass 

을 그 이유는 우리가 사용하는 모든 cargo code을 제거하는 것이 좋다 :

location = game[direction] 
direction = direction.lower() 

우리는 두 번째로 모든 시간을 우리는 중격이 메시지를 종료 물어 짜증나려고하고 동일한 메시지를 요청, 우리는 10 줄 이상 소문자로를 정의 할 수 소문자로 방향을 원한다면.그래서 불필요한 선을 제거한 후 우리가 얻을 : 여기
game = {"north" : "North leads to garden.", 
     "south" : "South leads to the kitchen.", 
     "east" : "East leads to the dining room.", 
     "west" : "West leads to the living room." 
} 

direction = "" 

while direction != "quit": 
     try: 
      direction = raw_input("Enter your direction: ").lower() 
      print game[direction] 
     except KeyError: 
      direction = raw_input("The direction you have entered is invalid\nEnter a direction or quit to exit: ") 

는 또한 방향이 키 정보 그대로 불필요한이다이 경우에 위치 변수를 제거했습니다. 또한 존재하지 않는 Key를 인쇄하려고 할 때 KeyError가 여전히 발생합니다. 당신은 당신이 그것을 할 수 있도록 사전에 액세스하는 동안 먼저 변수를 설정할 필요가 없습니다 .lower() 전화를 원한다면

그냥 또한 참고 :

print game[direction].lower() 
+0

프로그램이 방향을 요청할 때 while 문을 작성하려고합니다. 사용자가 "quit"이라는 단어를 입력하면 종료는 방향이 아니기 때문에 프로그램이 자동으로 종료되거나 종료됩니다. 사용자가 올바른 방향을 입력하면 메시지로 표시되거나 사용자가 잘못된 방향이나 사전에없는 방향을 입력하면 사용자가 방향을 다시 입력하라는 메시지가 표시됩니다. –

+0

현재 내 공간을 사용하지 않을 경우 들여 쓰기를 탭의 4 칸으로 전환하면 조언을 듣고 다시 내 질문을 업데이트했습니다. 그런 다음 코드를 스택에 복사 할 때 복사하려는 코드의 전체 섹션을 선택하고 추가 탭을 추가하십시오. 이렇게하면 코드에 필요한 4 개의 들여 쓰기 공간이 추가되고 해당 코드를 사이트에 복사하면 들여 쓰기가 정확 해지고 사람들이 당신을 도울 수 있습니다. 행운을 빌어 요 – Noelkd

+0

@ 루이 코스타 왜이 대답을 받아 들일 수 없는지? – Noelkd

0

어쨌든 입력을 기다리는 경우, 단순히 "if"를 종료하는 것이 더 쉽고, "elif"는 실제 방향이고 간단한 "else"는 횡설수설하면 입력하는 것이 더 쉽습니다.

관련 문제