建立密碼驗證器
你的團隊正在為一個網站開發身分驗證系統。為了確保使用者帳號安全,你需要建立一個 validate_password() 函式,用來檢查密碼是否符合最低安全需求。該函式應驗證密碼是否至少有 8 個字元,且包含至少一個來自 string 模組之 punctuation 集合的特殊字元。
string 模組以及測試密碼變數 user_password 已經幫你匯入。
本練習屬於課程
Intermediate Python for Developers
練習說明
- 完成
validate_password()函式,檢查密碼是否至少有 8 個字元。 - 加上一個迴圈,檢查密碼中的任何字元是否存在於
string.punctuation。 - 以
user_password呼叫該函式,並將結果儲存到is_valid。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def validate_password(password):
# Check if password is at least 8 characters long
if ____(____) >= 8:
# Check if password contains a special character
for char in password:
if char in string.____:
return True
return False
# Call the function and store the result
is_valid = ____(____)
print("Is the password valid? ", is_valid)