如何更改或覆盖输入密码

时间:2014-05-15 03:18:28

标签: python-3.x input

如何在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()

1 个答案:

答案 0 :(得分: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'
>>> 
相关问题