私はちょうどPythonを学び始めました。私のコードが動作している間、私はコード行を減らしたいと思います。私はlistメソッドを使うことを考えていましたが、実際には解決策を思いつくことができませんでした。私は事前に検索してみましたが、私に関連するものは見つけられませんでした。Python - 長いif-elifコード行を減らす
私のコードでは、1つのスペースを別のスペースに移動するような感じです。可能な動きは方向によって決定されます。私がポイントの動きを決定するために行ったことは、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')
ありがとうございました!