Password Generator.

If you are searching for ideas for a Python mini project on the internet, this would be one of the common search results. This is my take on a simple programme to generate passwords.

A password that is considered to be of sufficient complexity typically consists of the following:
– At least 1 upper case letter character
– At least 1 numerical character
– At least 1 symbol character
– Password to be of a certain length (e.g. at least 12 characters in length)

Let us consider the block of code below.

Line 6 imports the random module that will be used to randomly select the characters from each type of characters.
Line 9 to 11 each creates a string with each type of characters – letters, numbers, and symbols.
Line 13 stores the required length of the password as an integer variable.
Similarly, Line 14 and 15 stores the desired number for the letters and numbers type of character as integer variables. It is not required to ask for an input for the desired number for the symbols type as it is just the remaining number of characters. (Note: it might be worth including a try-except error here to ensure that the total number of characters adds up to the required length of the password.)

Line 21 to 33 describes a function that accepts two arguments – the desired number of characters, and the character type.
Line 22 creates an empty list that will store the characters to be chosen.
Line 23 uses a for loop, with the number of iterations correspond to the number of characters to be chosen. Line 24 first creates a number as the index for the string in the character type; this index number starts from 0 to one less than the length of the character type string. Line 25 then selects the character corresponding to the random index chosen.
For Line 26 to 31, another random number is used together with a if-else conditional to determine if the upper case or lower case will be chosen. This section will have no effect for the number and symbol character type. This short nested loop will have minimal impact on the total computation time given the relatively short length of the password. In Line 26, there is a 50% chance of choosing an upper case or lower case for each of the letters; this probability can be changed accordingly to suit your needs.

Finally Line 32 prints the list of characters chosen on the IPython console, and Line 33 returns the list for the next part of the code.

In the next part of the code, each of the lists with characters chosen for each character type is assigned to a variable in Line 36 to 38.
Line 43 concatenate these lists together, with Line 44 using the shuffle function in the random module to randomised their sequence.
Lastly, Line 45 converts the randomised list to a string with the eventual password.

An example of how the code will execute is shown below:

Is there any way to make the above codes more concise and elegant? Feel free to comment.

Leave a comment