2016-10-17 9 views
0

whileループを最初からやり直すことができません。関数の先頭に戻るためのループを作成する方法python

最初の試み

def start() : 

if choice in weapon: 
    print('You have taken the ') + choice + (',this is now in your backpack.\n') 
    inventory.append(choice) 

else: 
    print("Uh oh, I don't know about that item") 

start() 

が第二の試み

the_choice = False 
while not the_choice: 
if choice in weapon: 
    print('You have taken the ') + choice + (',this is now in your backpack.\n') 
    inventory.append(choice) 
    the_choice = True 
    # boom no loop needed 
else: 
    print("Uh oh, I don't know about that item") 
    the_choice = False 

私はちょうどそれを把握することができないよう、すべてのヘルプは高く評価され、感謝

+1

このコードは、コンピュータ上のファイルとまったく同じようにインデントされていますか?インデントはPythonでは本当に重要で、あなたの問題の原因になる可能性があります。 –

+0

私はビジュアルスタジオで符号化していますが、インデントは正しいと思われます。 – Tom

+0

ビジュアルスタジオは一般的にはPython用に作られていません...それだけでいいエディタがあるわけではありません。 – Aaron

答えて

2

あなたの第二の試みは近いように見えますが、すべての項目が完了したらesapeが必要ですが、あなたのスペースを見てください:ifはwhileの中にあります:(このコードはテストされていません、ちょうど推論を表示する...)

私は、Visual Studioが最高のpythonエディタではないかもしれませんコメント
choice = next_choice() 
found = false 
while not found: 
    if choice in weapon_stash: 
     inventory.append(choice) 
     found = True 
    else: 
     choice = next_choice() # get from user? 
     if choice == None: 
      break; # break out on some condition otherwise infinite loop 

# found is now either true (a thing was found), or false (the user quit) 
+2

'while found&:' ??? – ShadowRanger

+1

'False'ではなく' false'です。また、 'found'がfalseとして開始するため、これは決して実行されません。私はあなたが '見つからない間に: 'を探していると思います。 –

+1

上記のコードはfalseを定義するエラーではありませんが、私はインデントエラーのおかげでみんなを訂正しました。 – Tom

2

理由は、他のエディタは、あなたの最初の試みで、あなたの関数定義start()後にインデントを増加させなかった、また、あなたが後にインデントなかったことを警告しているだろうということです2回目の試行でwhileループが開始されます。あなたの問題を説明するのに役立つエラーメッセージを含めることは常に助けになりますが、私が推測するならば、あなたはIndentationErrorメッセージの何かを得ています。

インデントは、Pythonコーディングの最も重要な概念の1つであり、javaまたはC++の中括弧と同じ目的を果たします。 Wikipediaには、それを行う方法のかなり簡単な説明があります。

そこに多くの偉大なものがありますが、編集者として、私はspyderの個人的なファンです:Pycharmpydev、など。

0

第二の試みでのみインデントの障害があります。 以下のコードを試してください。

the_choice = False 
while not the_choice: 
    if choice in weapon: 
     print('You have taken the ') + choice + (',this is now in your backpack.\n') 
     inventory.append(choice) 
     the_choice = True 
     # boom no loop needed 
    else: 
     print("Uh oh, I don't know about that item") 
     the_choice = False 

ユーザーがリスト(武器)にない値を入力し続ける場合は、以下のようにすべてのFalseするカウンタを入れて、更新することができますので、これは、一定のループでスタックします。

counter=0 
the_choice = False 
while not the_choice: 
    if choice in weapon: 
     print('You have taken the ') + choice + (',this is now in your backpack.\n') 
     inventory.append(choice) 
     the_choice = True 
     # boom no loop needed 
    else: 
     print("Uh oh, I don't know about that item") 
     the_choice = False 
     counter=counter+1 

    if counter >= 3: 
     print('You have made 3 wrong attempts ') 
     break 
+0

ありがとうございます、これは私のリスト(武器)の中で何かを選ぶとうまくいくと思われますが、私は一定のループを持っています。 – Tom

+0

あなたは休憩声明を使用することができます.. 私は私の答えを更新します。 –

関連する問題