1

I have this chunk of code I'm trying to get to work and I need to use the 'password' variable in both of the if statements but I continue to get "NameError: name 'password' is not defined" (I'm fairly new to coding) I know there's probably a lot of ways I could improve this written in python 3.8 by the way

option = str(input("do you want a new password? y/n: "))
if option in ['y', 'Y']:
def generatepassword():
    digit = int(input("How long do you want the password? (integer only)"))
    for i in range(digit):
        char = random.choice(string.ascii_letters+string.digits+string.punctuation)
        (password) = char
        print(password)
generatepassword()

if option in ['n', 'N']:
password = str(input("Password: "))

final = str(input("Is this information correct?: "))

if final in ['y', 'Y']:
f = open("passwords.txt", "a")
f.write (password)
f.write ('\n')
f.close
f = open("email.txt", "a")
f.write(email)
f.write('\n')
f.close
f = open("web.txt", "a")
f.write(website)
f.write('\n')
f.close
bad_coder
  • 8,684
  • 19
  • 37
  • 59
kimo cruz
  • 11
  • 1

1 Answers1

2

Password is out of scope and needs to be defined outside the if statement.

password = ''
option = str(input("do you want a new password? y/n: "))
if option in ['y', 'Y']:
    def generatepassword():
        result = ''
        digit = int(input("How long do you want the password? (integer only)"))
        for i in range(digit):
            char = random.choice(string.ascii_letters+string.digits+string.punctuation)
            result += char
            print(char)
        return result

    password = generatepassword()

if option in ['n', 'N']:
    password = str(input("Password: "))
nbrix
  • 301
  • 2
  • 6