我编写了一个小密码生成器,您可以将密码及其服务保存在名为“password.txt”的文件中。每次运行程序时,文件都保持空白。当我删除文件并再次运行程序时,文件“password.txt”已创建但仍为空白。
import random
letters = "1 2 3 4 5 6 7 8 9 Q W E R T Z U I O P A S D F G H J K L Y X C V B N M q w e r t z u i o p a s d f g h j k l y x c v b n m : ; , . 0".split()
def checkNumb(string):
for i in string:
x = i.isdigit()
if x == True:
return True
def createPassword():
global letters
password = ""
i = 0
passLength = random.randint(7, 10)
while i < passLength:
passLetter = random.choice(letters)
password += passLetter
i += 1
x = checkNumb(password)
if x != True:
password = createPassword()
return password
print("What is the name of the service?")
service = input()
password = createPassword()
print(password, "will be your password for", service)
file = open("password.txt","a")
file.write(service + ": " + password)
file.close()
另外,因为我是初学者,如果有人能指出我在这段代码中可以做的一些改进,那将是一个很大的帮助。
编辑:while语句上的缩进错误只是我在将代码复制到此处时犯的错误。该程序没有缩进错误。感谢asongtoruin提醒我。
答案 0 :(得分:1)
只是一个小的缩进错误
import random
letters = "1 2 3 4 5 6 7 8 9 Q W E R T Z U I O P A S D F G H J K L Y X C V B N M q w e r t z u i o p a s d f g h j k l y x c v b n m : ; , . 0".split()
def checkNumb(string):
for i in string:
x = i.isdigit()
if x == True:
return True
def createPassword():
global letters
password = ""
i = 0
passLenght = random.randint(7, 10)
while i < passLenght:
passLetter = random.choice(letters)
password += passLetter
i += 1
x = checkNumb(password)
if x != True:
password = createPassword()
return password
print("What is the name of the service?")
service = input()
password = createPassword()
print(password, "will be your password for", service)
file = open("password.txt","a")
file.write(service + ": " + password)
file.close()
这有效,请查看createPassword()
中的while缩进输出
python write_file.py
What is the name of the service?
service1
SCawELnU7f will be your password for service1
文件内容:
service1: uj.voSK38
另请参阅此链接,了解文件追加差异
答案 1 :(得分:0)
经过测试的while i < passLenght:
代码缩减一次,并且它以inteneded