2014-05-15 38 views
0

如何在python中更改密碼?我試圖更改密碼,但它使用初始密碼。如何在代碼中實現新密碼?如何更改或覆蓋輸入密碼

def password(): 
    pw = input("Enter Password: ") 
    if pw == initial_pw: 
     print("Initializing....") 
     time.sleep(0.5) 
    else: 
     print("Access Denied! Wrong Password!") 
     password() 

def Setting(): 
    pw = input("Enter Old Password: ") 
    if pw == initial_pw: 
     new_pw = input("Enter New Password: ") 
     print (new_pw) 
     print ("Password has been changed.") 
    else: 
     print ("Sorry, you have just entered an invalid password.") 
     Setting() 

initial_pw = input("Create New Password: ") 
print("Create Successful.") 
while True: 
    password() 

    print("Press 1 to change password") 
    choice = int(input("Please choose an option: ")) 
    if choice == 1: 
     Setting() 
+0

何時以及爲什麼要更改它? –

+0

我希望用戶能夠更改密碼以擁有更安全的系統。這個密碼基本上是爲了防止入侵者。 – Newcomer

回答

0

剛剛從Setting()返回密碼,並將其分配給新的密碼:

import time 

def password(): 
    pw = input("Enter Password: ") 
    if pw == initial_pw: 
     print("Initializing....") 
     time.sleep(0.5) 
    else: 
     print("Access Denied! Wrong Password!") 
     password() 

def Setting(): 
    pw = input("Enter Old Password: ") 
    if pw == initial_pw: 
     new_pw = input("Enter New Password: ") 
     print (new_pw) 
     print ("Password has been changed.") 
    else: 
     print ("Sorry, you have just entered an invalid password.") 
     Setting() 
    try: 
     return new_pw 
    except UnboundLocalError: 
     return pw 

initial_pw = input("Create New Password: ") 
print("Create Successful.") 
while True: 
    password() 

    print("Press 1 to change password") 
    choice = int(input("Please choose an option: ")) 
    if choice == 1: 
     initial_pw = Setting() 

我也建議使用get pass模塊如果你關心密碼安全性。它可以防止字符回聲:

>>> password = input('Enter your password: ') 
Enter your password: mypassword 
>>> password 
'mypassword' 
>>> import getpass 
>>> password = getpass.getpass('Enter your password: ') 
Enter your password: 
>>> password 
'mypassword' 
>>> 
+0

在pw = input(「輸入舊密碼:」)期間輸入密碼錯誤的那一刻,我會在賦值之前引用UnboundLocalError:本地變量'new_pw'。我該如何解決 ? – Newcomer

+0

@ user3611307檢查我的更新 –

+0

哦謝謝,我嘗試把全局new_pw,它也可以。無論如何感謝您的幫助。非常感激 – Newcomer

相關問題