我正在自学python,我正在尝试创建一个密码生成器。我想要程序做的是,生成一个随机密码并将其保存到文本文件中。我在获取密码以保存到文本文件方面有什么问题。我能够获得一个生成的密码,但是我在text_file file.write( output ) NameError中得到了一个错误代码:虽然我已经定义了输出,但没有定义名称'output‘。如果有人能告诉我我做错了什么,我会很感激的。如果需要更多的信息,请告诉我。谢谢
import random
import string
# Generates a password from random.choice
length = int(input('How long do you want your password? '))
x = (string.ascii_letters + string.digits + string.punctuation)
def password():
for i in range(length):
output = print(random.choice(x),end='')
# Saves password to text file
def text_file():
print("Would you like to save your password to a text file?")
answer = input('y/n: ')
if answer == 'y':
print("One moment...")
file = open("Password.txt","a")
file.write(output)
file.close()
if answer == 'n':
print("...")
else:
print("Please input y or n...")
password()
print()
print()
text_file()产出:
How long do you want your password? 18
lsR~P4Mj#K7xg3_]go
Would you like to save your password to a text file?
y/n: y
One moment...
Traceback (most recent call last):
File "C:Password Generator.py", line 41, in <module>
text_file()
File "C:Password Generator.py", line 26, in text_file
file.write(output)
NameError: name 'output' is not defined发布于 2020-06-04 02:33:56
该函数中没有定义output。把它传进去,它就能用了。
发布于 2020-06-04 02:36:27
变量输出是局部变量。您需要将其定义为全局函数,或者使用参数将值传递给text_file函数。
https://stackoverflow.com/questions/62185913
复制相似问题