A password generator picks characters at random from a set of allowed characters. This version also makes sure every password has at least one lowercase letter, one capital letter, one digit and one symbol.
The program
import random import string # fixed seed so the output matches this page; remove it for real use random.seed(7) def make_password(length=12): if length < 4: raise ValueError("length must be at least 4") groups = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string.punctuation] # one character from each group, so every password contains all four kinds chars = [random.choice(group) for group in groups] all_chars = "".join(groups) chars += random.choices(all_chars, k=length - len(groups)) random.shuffle(chars) return "".join(chars) for length in [8, 12, 16]: print(length, make_password(length))
8 E6YgfIk$ 12 6l$2|LRu:6`c 16 9Cf-QdD3OZ-tJ"Sf
How it works
- The
stringmodule has ready-made sets of characters:string.ascii_lowercaseis"abcdefghijklmnopqrstuvwxyz",string.digitsis"0123456789", andstring.punctuationholds symbols such as!,#and%. random.choice(group)picks one character.random.choices(all_chars, k=...)picks several, and the same character can come up more than once.- The first four characters always come in the same order (lowercase, capital, digit, symbol).
random.shuffle(chars)mixes the list so the order is random too. - A password shorter than 4 cannot hold one of each kind, so the function raises a
ValueErrorinstead of breaking the rule.
For real passwords: use secrets
The random module is made for games and simulations. Its numbers can be predicted if someone knows enough of its earlier output. For passwords, tokens and keys, use the secrets module, which uses the operating system's secure random source:
import secrets import string alphabet = string.ascii_letters + string.digits + string.punctuation password = "".join(secrets.choice(alphabet) for _ in range(16)) print(password)
This block has no output shown because it prints a different password every time it runs. secrets has no seed, and that is the point: nobody can repeat its results.