将if语句添加到while循环

时间:2017-02-28 19:35:43

标签: python if-statement while-loop

此代码的前提是要求输入一个名称,最多3次。

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

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

3 个答案:

答案 0 :(得分:4)

如果您想再试一次,那么您需要捕获该值。

password = input ('Try again: ')

否则,while循环永远不会停止。

此外,Python有while-else,可以帮助您调试问题

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

答案 1 :(得分: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  

答案 2 :(得分:0)

这是一种有趣的方式,而不是使用计数器,您可以创建一个包含三个元素的列表,$$watchers测试确保仍有剩余元素:

while