그러나 나는 문제가 생각 :
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()
"quit"은 언제 입력합니까? –
코드를 들여 쓰기 할 수 있습니까? 우리는 루프 외부에 무엇이 있는지, 루프에 실제로 무엇이 있는지 모릅니다. 명령문과 동일합니다. – Paco
프로그램의 시작 부분에 "quit"을 입력해야합니다. –