我的代码工作正常,但我肯定有不必要的重复代码。我想使用函数,所以我没有重复的代码。对于如何使我的密码生成器代码更简洁的任何建议,我将不胜感激。
我尝试浏览其他论坛,但找不到所需的答案。
import string
import random
lowerCase = string.ascii_lowercase[:26]
upperCase = string.ascii_uppercase[:26]
numberList = ["1","2","3","4","5","6","7","8","9"]
specialCharacters = ["*","&","@","!"]
responseList = ["weak","medium","strong"]
randomCharacters =[ ]
i=0
while True:
choice = input("Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong. ")
if choice in responseList:
if choice == "weak":
while i<=5:
randomLetterLower = random.choice(lowerCase)
randomCharacters.append(randomLetterLower)
i += 1
elif choice == "medium":
while i<=4:
randomLetterLower = random.choice(lowerCase)
randomCharacters.append(randomLetterLower)
randomLetterUpper = random.choice(upperCase)
randomCharacters.append(randomLetterUpper)
i += 1
elif choice == "strong":
while i<=1:
randomLetterLower = random.choice(lowerCase)
randomCharacters.append(randomLetterLower)
randomLetterUpper = random.choice(upperCase)
randomCharacters.append(randomLetterUpper)
randomNumber = random.choice(numberList)
randomCharacters.append(randomNumber)
randomSpecialCharacter = random.choice(specialCharacters)
randomCharacters.append(randomSpecialCharacter)
i += 1
output = " ".join(randomCharacters)
print(output)
i = 0
randomCharacters =[]
else:
break
输出实际上可以找到并得到我想要的东西。