2017-02-28 288 views
0

此代码的前提是要求输入名称,最多尝试3次。将if语句添加到while循环

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') 

我只能输入正确的密码,第一次尝试返回'做得好'。在另外两次尝试中,它会返回为“再次尝试”。如果输入任何尝试,我怎样才能让它恢复得很好?

+0

仅供参考,'企图=企图-1'可以更简单地写为'企图 - = 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

这是一个有趣的方式来做到这一点,而不是使用计数器时,您可以创建一个包含三个元素的列表,并且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()