ユーザーに辞書に存在するキーを回答するまでinputを求める方法

辞書のValueがTrueかFalseか

以下のようなプログラミングをPythonで作っています。

このような辞書があります。

python

1dictionary = {"A1": True, "A2": False, "A3": False, "A4": False, "B1": True, "B2": False, "B3": False, "B4": True, "C1": False, "C2": False, "C3": False, "C4": False, "D1": True, "D2": True, "D3": True, "D4": False}

Key = ポジション
Value = True / False

まずはinput関数(OUTPUT_PROMPT)を使ってユーザーにポジション(Key)を聞きます。
そのポジションがFalseだったら、再度input関数(OUTPUT_PROMPT)で新しいポジションを聞きます。
インプットされたものが辞書に存在しない場合も再度input関数(OUTPUT_PROMPT)で新しいポジションを聞きます。
ポジションがTrueだったら"You won."を返して終了します。

expected output:

python

1Write the position: A1 #A1 = True2You won.3 4Write the position: A2 #A2 = False5Write the position: C1 #C1 = False6Write the position: D3 #D3 = True7You won.8 9Write the position: A5 #A5 = not valid10Write the position: A4 #A4 = False11Write the position: D5 #D5 = not valid12Write the position: A1 #A1 = True13You won.

試したこと

python

1dictionary = {"A1": True, "A2": False, "A3": False, "A4": False, "B1": True, "B2": False, "B3": False, "B4": True, "C1": False, "C2": False, "C3": False, "C4": False, "D1": True, "D2": True, "D3": True, "D4": False}2 3OUTPUT_PROMPT = "Write the position: "4OUTPUT_WIN = "You won."5 6 7def game():8 while True:9 position = input(OUTPUT_PROMPT)10 try:11 if dictionary[position] == False:12 continue13 if dictionary[position] == True:14 return OUTPUT_WIN 15 except ValueError:16 continue17 18game()

while True と try/except の使い方があまりよく分かりません。<<インプットされたものが辞書に存在しない場合も再度input関数(OUTPUT_PROMPT)で新しいポジションを聞きます。>>をどうループすればいいのかが分からなくて困ってます。

コメントを投稿

0 コメント