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

2024-04-27 05:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这段代码,我正试图开始工作,我需要在两个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

Tags: 代码intxtyoucloseinputstringif
1条回答
网友
1楼 · 发布于 2024-04-27 05:42:19

密码超出范围,需要在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: "))

相关问题 更多 >