需求:Python實(shí)現(xiàn)三次密碼驗(yàn)證,每次驗(yàn)證結(jié)果需要提示,三次驗(yàn)證不通過需要單獨(dú)提示
代碼如下:
user = '張無忌'
password = '12345678'
confirm_flag = True
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 = False # 驗(yàn)證成功后更改confirm_flag,則不打印驗(yàn)證失敗提示
break
else:
print('Invalid user or password!')
if confirm_flag:
print('Input the invalid password more than three times')
驗(yàn)證成功結(jié)果如下:

三次驗(yàn)證失敗結(jié)果如下:

上面代碼使用for-break循環(huán)、if/else的條件判斷來實(shí)現(xiàn)需求
三次驗(yàn)證失敗輸出提示部分代碼還可以優(yōu)化,下面使用for-else循環(huán)優(yōu)化,代碼如下:
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')
驗(yàn)證成功結(jié)果如下:

三次驗(yàn)證失敗結(jié)果如下:

for/while循環(huán)之后的else語句,只有在循環(huán)正常結(jié)束后才會(huì)執(zhí)行,如果中間使用了break語句跳出循環(huán),則不會(huì)執(zhí)行
上面的代碼中,驗(yàn)證成功時(shí),通過break語句跳出了循環(huán),所以不會(huì)打印else之后的驗(yàn)證失敗語句,而三次驗(yàn)證未通過時(shí),循環(huán)正常結(jié)束,則會(huì)執(zhí)行else之后的提示語句
以上就是python實(shí)現(xiàn)三次密碼驗(yàn)證的示例的詳細(xì)內(nèi)容,更多關(guān)于python 密碼驗(yàn)證的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- python實(shí)現(xiàn)密碼驗(yàn)證合格程序的思路詳解
- Python使用selenium實(shí)現(xiàn)網(wǎng)頁用戶名 密碼 驗(yàn)證碼自動(dòng)登錄功能
- python連接mongodb密碼認(rèn)證實(shí)例