2016-07-14 10 views
-1

少し話題があります:私はPythonでコードを作成しなければなりません。これは、ユーザーが学校プロジェクトの電話機のトラブルシューティングに役立ちます。ユーザーは、プログラムが質問する質問に対してのみ「はい」または「いいえ」と答えなければなりません。無限ループ中Python

私は、「はい」または「いいえ」以外のものを入力すると、一度表示する代わりにループが無限ループするようになり、ユーザーが「はい」と入力すると次の質問に移動します。または 'いいえ'。

コードがまだ完成していないため、いくつかのアドバイスや質問が欠落しているようです。

EDIT:コードは正しく機能します。あなたの答え、みんなありがとう!彼らは本当に役に立ちました!

phoneFault = raw_input("Is your phone physically damaged?") 
while phoneFault != "Yes" and phoneFault != "No": 
    print("Error; you can only answer 'Yes' or 'No' to the questions.") 
if phoneFault == "Yes" or phoneFault == "yes": 
    phoneFault = raw_input("Is your phone wet?") 
    if phoneFault == "Yes" or phoneFault == "yes": 
     phoneFault = raw_input("Are you able to turn it off?") 
     if phoneFault == "Yes" or phoneFault == "yes": 
      print("Send the phone to the manufacturer and ask if they can fix it.") 
     elif phoneFault == "No" or phoneFault == "no": 
      print("Dry the phone, and then wait for the phone to run out of power and then restart it.") 
+0

while条件が決して変わらないように、 'phoneFault'の値を決して変更しません。その間に別のphoneFault = raw_input( "Is ...")を追加してみてください。 – dave

答えて

2
while phoneFault != "Yes" and phoneFault != "No": 
    print("Error; you can only answer 'Yes' or 'No' to the questions.") 

この行は犯人です。 "Yes"または"No"以外のものを入力すると、このwhileループに入ります。このwhileループの間に、phoneFaultの値は変更されないため、エラーメッセージを無限に出力し続けます。

このwhileループ中にphoneFaultの値を変更する機能を追加すると、問題が解決されます。

0

無限ループが発生した場合はいつでも、条件を見て、その条件を変更する可能性があるものを見てください。あなたは、おそらくこのようなものは、ループ内raw_inputを入れたい:

ではないが非常にユーザーフレンドリーだ
phoneFault = None 
while phoneFault != "Yes" and phoneFault != "No": 
    phoneFault = raw_input("Is your phone physically damaged?") 
    print("Error; you can only answer 'Yes' or 'No' to the questions.") 

。あなたが代わりにこの検討するかもしれない資本YまたはN.取得する> <シフトを押さ:あなただけif条件ごとに2つの答えを持っていますが

phoneFault = None 
while phoneFault != "yes" and phoneFault != "no": 
    phoneFault = raw_input("Is your phone physically damaged (Yes/No)? ").lower() 
+0

ユーザー入力のために再ポーリングする前にエラーを印刷したくないですか? – Tyler

+0

2番目の解決策では、私は不要なエラーメッセージをドロップしました。 – cdarke

0

を、私は個人的にif phoneFault in ('Yes','yes'):メンバーシップのテストを好みます。これにより、コードが読みやすくなります。 phoneFaultを 'yes'や 'no'のようなものとマッチさせたい場合は、reモジュールの正規表現に興味があるかもしれません。