您的位置:首页技术文章
文章详情页

python实现三次密码验证的示例

【字号: 日期:2022-06-20 16:40:48浏览:3作者:猪猪

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

代码如下:

user = ’张无忌’password = ’12345678’confirm_flag = Truefor 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 = False # 验证成功后更改confirm_flag,则不打印验证失败提示break else:print(’Invalid user or password!’)if confirm_flag: print(’Input the invalid password more than three times’)

验证成功结果如下:

python实现三次密码验证的示例

三次验证失败结果如下:

python实现三次密码验证的示例

上面代码使用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’)

验证成功结果如下:

python实现三次密码验证的示例

三次验证失败结果如下:

python实现三次密码验证的示例

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

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

以上就是python实现三次密码验证的示例的详细内容,更多关于python 密码验证的资料请关注好吧啦网其它相关文章!

标签: Python 编程
相关文章: