Kinaro's blog of things

Create a password generator using under 20 lines of code

June 08, 2019


  • Python3
  • Text editor

Time to roll

  1. Fire up your editor of choice.
  2. Create a file with a .py extension
  3. Enter the following code in your blank file. I’m currently using Ubuntu, so you can safely omit the first line if you are using Windows. PassGen Code
  4. We start by importing the random module, which implements the choice method.
  5. Next we create a string of characters, inclusive of symbols. These will be chosen randomly in order to come up with a password.
  6. passGen is a function that takes one parameter (pass_len), which determines the length of our password. Function definition starts with the def keyword.
  7. In the passGen function, we use a for loop to iterate over a range of 0 to pass_len. the end='' tells Python that we do not want a newline at the end of each character.
  8. The main function asks the user the legth of the password they need, then passes that requirement to the passGen function.