Solution Design First, you’ll need to create constant strings for each category of characters required by the
exercise:
Lowercase letters: abcdefghijklmnopqrstuvwxyz (26 characters)
Uppercase letters: ABCDEFGHIJKLMNOPQRSTUVWXYZ (26 characters)
Numbers: 1234567890 (10 characters)
Special characters: ~!@#$%^&*()_+ (13 characters)
Next, create a string that concatenates all four strings into one 75-character string. These
variables are constants in that they aren’t meant to have their contents changed. By convention,
constant variables are typed with ALL_UPPERCASE names and have underscores to separate words
by convention. Constants are often created in the global scope outside of all functions, rather than as
local variables inside a particular function. Constants are commonly used in all programming
languages, even though the term ―constant variable‖ is a bit of an oxymoron.
The first line of the generatePassword() function should check if the length argument is
less than 12, and if so, set length to 12. Next, create a password variable that starts as an empty
list. Then randomly select a character from the lowercase letter constant using Python’s
random.randint()
function to pick a random integer index from the constant’s string. Do this for
the other three constants as well.
To guarantee that the final password has at least one character from each of the four categories,
we’ll begin the password with a character from each category. Then we’ll keep adding characters from
the combined string until the password reaches the required length.
But this isn’t completely random since the first four characters are from predictable categories.
To fix this issue, we’ll call Python’s random.shuffle() function to mix up the order of the
characters. Unfortunately, the random.shuffle() function only works on lists, not strings, so we
build up the password from an empty list rather than an empty string.
In a loop, keep adding a randomly selected character from the concatenated string with all
characters until the password list is the same length as length. Then, pass the password list to
random.shuffle()
to mix up the order of the characters. Finally, combine this list of strings into a
single string using ''.join(password) and return it.