python實現三次密碼驗證的示例
需求: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’)
驗證成功結果如下:
三次驗證失敗結果如下:
上面代碼使用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之后的提示語句
以上就是python實現三次密碼驗證的示例的詳細內容,更多關于python 密碼驗證的資料請關注好吧啦網其它相關文章!
相關文章: