我正在研究一个简单的密码生成脚本,我实际上是在尝试使用名为password
的全局字符串变量,但我不确定我是否正确使用它,因为我收到此错误:
File "C:\Users\bkrause080\Desktop\Free Time Projects\LearningPythonProjects\passwordGenerator.py", line 34, in <module>
if __name__ == "__main__": main()
File "C:\Users\bkrause080\Desktop\Free Time Projects\LearningPythonProjects\passwordGenerator.py", line 32, in main
print "Your strong password is: ", strong(lowercase, uppercase, numbers, specials)
File "C:\Users\bkrause080\Desktop\Free Time Projects\LearningPythonProjects\passwordGenerator.py", line 22, in strong
password += random.choice(lowercase).rstrip('\n') + random.choice(uppercase).rstrip('\n') + random.choice(numbers).rstrip('\n') + random.choice(specials).rstrip('\n')
UnboundLocalError: local variable 'password' referenced before assignment
这是我的源代码:
import random
lowercase = ['a', 'b', 'c', 'd','e', 'f', 'g', 'h', 'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
uppercase = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numbers = ['1','2','3','4','5','6','7','8','9','0']
specials = ['~','!','@','#','$','%','%', '^', '&','&','*','(',')','?','<','>','[',']']
password = ""
def weak():
with open("EnglishWords.txt", "r") as f:
weakWords = f.readlines()
password = random.choice(weakWords).rstrip('\n') + random.choice(weakWords).rstrip('\n')
return password
def medium(lowercase, numbers):
for i in range(0,4):
password += random.choice(lowercase).rstrip('\n') + random.choice(numbers).rstrip('\n')
return password
def strong(lowercase, uppercase, numbers, specials):
for j in range(0,3):
password += random.choice(lowercase).rstrip('\n') + random.choice(uppercase).rstrip('\n') + random.choice(numbers).rstrip('\n') + random.choice(specials).rstrip('\n')
return password
def main():
passStrength = raw_input("What strength password would you like? (weak/medium/strong): ")
if passStrength == 'weak':
print "Your weak password is: \n", weak()
elif passStrength == 'medium':
print "Your medium password is: ", medium(lowercase, numbers)
elif passStrength == 'strong':
print "Your strong password is: ", strong(lowercase, uppercase, numbers, specials)
if __name__ == "__main__": main()
我是python的新手,只有真正的java和C经验,所以任何信息都会非常感激!