Python实现三次密码验证

需求:Python实现三次密码验证,每次验证结果需要提示,三次验证不通过需要单独提示

代码如下:

user = '张无忌'
password = '12345678'
confirm_flag = False

for i in range(0, 3):
    user_input = input('user:')
    password_input = input('password:')
    if user_input == user and password_input == password:
        print('Welcome! %s' % user)
        confirm_flag = True  # 验证成功后更改confirm_flag,则不打印验证失败提示
        break
    else:
        print('Invalid user or password!')
if not confirm_flag:
    print('Input the invalid password more than three times')

验证成功结果如下:

三次验证失败结果如下:

上面代码使用for-break循环、if/else的条件判断来实现需求

三次验证失败输出提示部分代码还可以优化,下面使用for-else循环优化,代码如下:

user = '张无忌'
password = '12345678'

for i in range(0, 3):
    user_input = input('user:')
    password_input = input('password:')
    if user_input == user and password_input == password:
        print('Welcome! %s' % user)
        break
    else:
        print('Invalid user or password!')
else:
    print('Input the invalid password more than three times')

验证成功结果如下:

三次验证失败结果如下:

for/while循环之后的else语句,只有在循环正常结束后才会执行,如果中间使用了break语句跳出循环,则不会执行

上面的代码中,验证成功时,通过break语句跳出了循环,所以不会打印else之后的验证失败语句,而三次验证未通过时,循环正常结束,则会执行else之后的提示语句

while-else循环实现代码如下:

user = '张无忌'
password = '12345678'
counter = 0

while counter < 3:
    user_input = input('user:')
    password_input = input('password:')
    if user_input == user and password_input == password:
        print('Welcome! %s' % user)
        break
    else:
        print('Invalid user or password!')
    counter += 1
else:
    print('Input the invalid password more than three times')
posted @ 2021-04-29 14:48  弓长无忌  阅读(600)  评论(0编辑  收藏  举报