有没有一种更简单的方法来生成随机密码


import string
import random
characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
i = input('Please enter confirm (input 1) to proceed with password creation (or any to quit):n')
if i == 1:
print("Generating username and password....") 
length = int(input("Enter password length: "))
random.shuffle(characters)

password = []
for i in range(length):
password.append(random.choice(characters))

random.shuffle(password)

print("".join(password))
else:
exit

有没有一种更简单的方法来生成随机密码,在if语句中生成密码也不起作用,我该如何修复它。我还想能够调出我的密码,那么在我生成一个变量后,我该如何将其放入变量中呢。

这是作为函数的方法,因此您可以使用返回值执行任何操作:

import string
import random
characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
def genpassword(length):
random.shuffle(characters)
return ''.join(characters[:length])
length = int(input("Enter password length: "))
print("Generating username and password....") 
password = genpassword(length)
print(password)

评论中提到的random.choices选项是一个更好的实现。我将把它留给读者练习。

最新更新