2017-12-15 5 views
0

取得値は、ユーザーの値に基づいて、特定のフレーズを出力します

user_input = input("You decide: ") 

#functionも(間違った値の必要性ループが入力された)はループ <p>ユーザーが間違った値を入力した場合、最初からやり直すという文をループしようとします。私は立ち往生していて、コンピュータを投げ捨てることに近いですが、私は単純な修正があることを知っていますが、それを見つけることはできません。</p>

if user_input == 'A' or user_input == 'a': 
    print("With Uncle Sam in your corner you shall not fail...or I could be wrong?\nEither way lets get that Clock rolling") 
elif user_input == 'Q' or user_input == 'q': 
    mess = ("Well to heck with ya then!") 
    print(mess) 
elif user_input == 'B' or user_input == 'b': 
    print("May Mother Russia led you to a brighter future!\nLets begin shall we") 
elif user_input == 'C' or user_input == 'c': 
    print("Ahhhh..the lonley Red State....well all I can say is either they follow you or get regret ever doubting you!!\nBegin your reign") 

else: 
    print("Wrong Value!!!") 
を間違った値のエラーメッセージがある場合

答えて

0

あなたはストレートフォワードループ作成するcontinuebreakコマンドを使用することができます。

while True: 
    user_input = input("You decide: ") 
    if user_input == ... 
     print("With... 
    elif user_input == ... 
     print("Well... 
    else: 
     print("Wrong value!!!") 
     continue 
    break 

非常にPython的ではありませんが、あなたの現在のコードにフィットレトロう。ここで

はプログラムにより構成された別のバージョンである:

def query_and_response(prompt, responses): 
    while True: 
     try: 
      return responses[input(prompt).lower()] 
     except KeyError: 
      print('Wrong value!!! valid values are {0}'.format(responses.keys())) 

responses = { 
    'a': 'With Uncle Sam in your corner you shall not fail...or I could be wrong?\nEither way lets get that Clock rolling', 
    'b': 'May Mother Russia led you to a brighter future!\nLets begin shall we', 
    'c': 'Ahhhh..the lonley Red State....well all I can say is either they follow you or get regret ever doubting you!!\nBegin your reign' 
} 
print query_and_response("You decide: ", responses) 
+0

'return'は常に' while'に強制的に1回だけ実行されます...正しい? – NoobEditor

+0

@ NoobEditor、はい、関数からの戻り値はループを終了します。入力が応答辞書のいずれかのキーと一致しない場合、 'try except KeyError'は分岐します。 –

1

1つのオプションは、有効な入力があるまでwhile -loopに促し、その後、ユーザーの入力が有効な入力ではありませんかどうかを確認することであってもよいです受信:

user_input = raw_input("You decide: ").lower() 

while (user_input not in ['a', 'b', 'c', 'q']): 
    print("Wrong Value!!!") 
    user_input = raw_input("You decide: ").lower() 

if user_input == 'a': 
    print("With Uncle Sam in your corner you shall not fail...or I could be wrong?\nEither way lets get that Clock rolling") 
elif user_input == 'q': 
    mess = ("Well to heck with ya then!") 
    print(mess) 
elif user_input == 'b': 
    print("May Mother Russia led you to a brighter future!\nLets begin shall we") 
elif user_input == 'c': 
    print("Ahhhh..the lonley Red State....well all I can say is either they follow you or get regret ever doubting you!!\nBegin your reign") 
else: 
    print("Unhandled case") 

および印刷するきれいな方法は、非常に多くのif

の代わりに dictを使用することです

これはあまりにも無邪気であるでしょう!

関連する問題

 関連する問題