방금 Python을 배우기 시작했으며 코드가 작동하는 동안 코드 줄을 줄이려고합니다. 목록 방법을 사용할 생각 이었지만 실제로 해결책을 찾지 못했습니다. 미리 검색해 보았지만 광산과 관련된 것을 찾을 수 없었습니다.Python - 긴 if-elif 코드 줄 줄임
내 코드의 경우 한 공간에서 다른 공간으로 이동하는 것과 같습니다. 가능한 움직임은 지시에 의해 결정됩니다. 요점의 움직임을 결정하기 위해 내가 한 일은 userPoint
(요점을 결정하는 부분)을 할당하는 것이 었습니다. 이동하려면 공백에 설정된 조건 (userInput.upper()
으로 표시되는 사용 가능한 유일한 방향)을 충족시켜야합니다. 그렇지 않으면 입력이 유효하지 않은 것으로 이동하고 인쇄하지 않습니다.
if userInput.upper() == 'QUIT':
break
elif userPoint == 0 and userInput.upper() =='EAST':
userPoint = 1
elif userPoint == 1 and userInput.upper() == 'WEST':
userPoint = 0
elif userPoint == 1 and userInput.upper() == 'EAST':
userPoint = 2
elif userPoint == 1 and userInput.upper() == 'SOUTH':
userPoint = 4
elif userPoint == 2 and userInput.upper() == 'WEST':
userPoint = 1
elif userPoint == 3 and userInput.upper() == 'SOUTH':
userPoint = 6
elif userPoint == 4 and userInput.upper() == 'NORTH':
userPoint = 1
elif userPoint == 4 and userInput.upper() == 'EAST':
userPoint = 5
elif userPoint == 5 and userInput.upper() == 'WEST':
userPoint = 4
elif userPoint == 5 and userInput.upper() == 'SOUTH':
userPoint = 8
elif userPoint == 6 and userInput.upper() == 'NORTH':
userPoint = 3
elif userPoint == 6 and userInput.upper() == 'EAST':
userPoint = 7
elif userPoint == 7 and userInput.upper() == 'WEST':
userPoint = 6
elif userPoint == 7 and userInput.upper() == 'EAST':
userPoint = 8
elif userPoint == 8 and userInput.upper() == 'WEST':
userPoint = 7
elif userPoint == 8 and userInput.upper() =='NORTH':
userPoint = 5
else:
print('Please input a valid direction.\n')
도움 주셔서 감사합니다.