2017-02-28 8 views
0

このコードの前提は、最大3回の試行で名前を要求することです。whileループへのif文の追加

password = 'correct' 
attempts = 3 
password = input ('Guess the password: ') 
while password != 'correct' and attempts >= 2: 
    input ('Try again: ') 
    attempts = attempts-1 
if password == 'correct':    #Where the problems begin 
    print ('Well done') 

私は、「よくできました」を返す最初の試行でしか正しいパスワードを入力できません。他の2つの試みでは、「もう一度やり直してください」と返されます。どのような試みでも入力した場合、どのようにして正常に戻ることができますか?

+0

FYI、 'attempts = attempts-1'は' attempts-= 1'としてより簡単に書くことができます – Alexander

答えて

4

もう一度やり直したい場合は、その値を取得する必要があります。

password = input ('Try again: ') 

それ以外の場合、whileループは決して停止しません。

また、Pythonはあなたの代わりに、これはそれを行うための楽しい方法で問題に

while password != 'correct' and attempts >= 2: 
    password = input ('Try again: ') 
    attempts = attempts-1 
else: 
    print('while loop done') 
    if password == 'correct':    #Where the problems begin 
     print ('Well done') 

それとも

attempts = 3 
password = input('Enter pass: ') 
while attempts > 0: 
    if password == 'correct': 
     break 
    password = input ('Try again: ') 
    attempts = attempts-1 
if attempts > 0 and password == 'correct': 
    print ('Well done') 
+0

ありがとう。入力にパスワードを割り当てた後( 'もう一度やり直す')、それは完全に機能しました。 –

0
attempts = 3 
while attempts > 1: 
    password = input("Guess password") 
    if password == "correct" and attempts > 2: 
     print("Well done") 
     break 
    else: 
     print("try again") 
    attempts = attempts - 1 
+1

あなたの答えを説明してください! –

+0

の試行回数は3回ですが、0回の試行が残っていると、ループから外れます。残りの試行回数が2回の場合は正常に印刷されますが、残りの試行回数が2回未満の場合は、もう一度試してから再度試行してください。 – Luv33preet

0

をデバッグに役立つ可能性がある、一方で、他にありカウンタを使用する場合は、3つの要素でリストを作成し、whileのテストで要素が残っていることを確認できます:

password,wrong,right = 'nice',['Wrong']*3,['you got it!'] 
while len(wrong)>0 and len(right)>0: 
    right.pop() if input('guess:')==password else wrong.pop() 
関連する問題