2016-12-14 4 views
0

whileループを使用するのに問題があります。私がしたいのは、プログラムが実行され、出力が提供されると、プログラムは「翻訳する単語を入力してください」に戻ります。Pythonのループが動作しない

while truecontinueを私が適切な場所と信じて使用したとき、単に出力を続けます。私が翻訳している言葉の希望は意味をなさない。

以下は、私が働いているコードです。 2番目のチャンクは、whileループを追加して問題に取り組む場所です。

def silly_alpha(): 
    print("Looks like we're going with the Impossible alphabet.") 
    word_trans = input('Please enter the word you wish to translate: ') 
    if word_trans.isalpha(): 
     for letter in word_trans: 
      print(impossible.get(letter.lower()), end=' ') 
    else: 
     print("There's no numbers in words. Try that again.") 

これは、問題のあるコード

def silly_alpha(): 
    print("Looks like we're going with the Impossible alphabet.") 
    while True: 
     word_trans = input('Please enter the word you wish to translate: ') 
     if word_trans.isalpha(): 
      for letter in word_trans: 
       print(impossible.get(letter.lower()), end=' ') 
       continue 
     else: 
      print("There's no numbers in words. Try that again.") 
      continue 
+2

'continue'をまったく使用する必要はありません。 – ettanany

+0

あなたは何を続けると思いますか? – polku

+0

'continue'は、最も内側のブロックを続けます。 'if'の場合の' for'反復と 'else'の場合の' while'です。 –

答えて

1

それはループを繰り返していて、翻訳する新しい単語を受け入れることです、あなたは、単にそれらのcontinue文を削除する必要があります。これをIDLEでテストしたところ、うまく動作します。

def silly_alpha(): 
    print("Looks like we're going with the Impossible alphabet.") 
    while True: 
     word_trans = input('Please enter the word you wish to translate: ') 
     if word_trans.isalpha(): 
      for letter in word_trans: 
       print(impossible.get(letter.lower()), end=' ') 
     else: 
      print("There's no numbers in words. Try that again.") 

ただし、無限ループが発生しました。ループを終了させるコマンドをユーザーが入力できるようにする方法を検討することをお勧めします。おそらく何かのように:

def silly_alpha(): 
    print("Looks like we're going with the Impossible alphabet.") 
    while True: 
     word_trans = input('Please enter the word you wish to translate, "x" to cancel: ') 
     if word_trans == 'x': 
      print('Exiting translation...') 
      break 
     elif word_trans.isalpha(): 
      for letter in word_trans: 
       print(impossible.get(letter.lower()), end=' ') 
     else: 
      print("There's no numbers in words. Try that again.") 
+1

ahhhhこれは意味があり、働いています。入力いただきありがとうございます! – hozayjgarseeya

+0

私はその違いを見て、何が変わったのかを見ています。 'word_trans'の前に' while True'を置く理由について説明できますか?後に配置すると、このループの問題が発生しますが、前に配置されている場合は、期待どおりに動作します。 – hozayjgarseeya

+1

あなたは繰り返し入力を求めたいので、ループが再び始まるたびに新しいものを入力したい場合は、 'word_trans'を一度割り当てることができます。その後同じ' word_trans'を繰り返しループします。 – Philipp

1

continueが最も近いループに適用され、このループでは、次の手順をスキップすることができます。

したがって、最初のcontinueは、ループの最後の命令であるため、に適用されます。これは無効です。

第2のcontinueは、ループの最後の命令であるので、効果がないので、while Trueに適用されます。

breakは、最も近いループであるを終了します。あなたの場合、while Trueと思います。

最初のcontinueを削除し、2番目の部分をbreakに置き換えてください。

関連する問題