Python 在两个不同的if语句中使用一个变量

Python 在两个不同的if语句中使用一个变量,python,python-3.8,Python,Python 3.8,我有这段代码,我正试图开始工作,我需要在两个if语句中使用'password'变量,但我继续得到“NameError:name'password'未定义” (我对编码相当陌生)顺便说一句,我知道有很多方法可以改进用python 3.8编写的代码 option = str(input("do you want a new password? y/n: ")) if option in ['y', 'Y']: def generatepassword(): digit =

我有这段代码,我正试图开始工作,我需要在两个if语句中使用'password'变量,但我继续得到“NameError:name'password'未定义” (我对编码相当陌生)顺便说一句,我知道有很多方法可以改进用python 3.8编写的代码

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

密码超出范围,需要在if语句之外定义

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: "))