Вопрос

How do I change password in python ? I tried to change the password but it uses the initial password. How do I implement the new password into the code.

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()
Это было полезно?

Решение

Just return the password from Setting(), and assign it to the new password:

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()

I would also suggest using the get pass module if you care about password security. It prevents character echo:

>>> password = input('Enter your password: ')
Enter your password: mypassword
>>> password
'mypassword'
>>> import getpass
>>> password = getpass.getpass('Enter your password: ')
Enter your password: 
>>> password
'mypassword'
>>> 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top