How to create a simple password generator using Python 3?

/ #Python


Creating a simple password generator using Python can be a fun exercise and it will teach you some basic Python.

What are we going to create?

We are going to create a very simple password generator. We're going to create a function which will return a random string based on a string of characters.

Importing the modules we need

Create a new file and start by adding these two lines:

import string
import random

The "random" module is used to choose a random character from a string of characters. The "string" module is used to generate a string of characters. I will show you what it looks like in a bit.

The generate function

Below the two import lines, we create a new function. Add these lines to your Python file:

def generatePassword():
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(10))

The first line is where we define the name of the function, we don't need any parameters. On line two, we create a variable called letters, this will contain a string of letters looking like this: "abcdefghijklmonopqrstuvwxyz". You can create your own if you want istead of using the "string.ascii_lowercase" function.

On the last line of the function, we start by creating a new empty string. It's a bit hard to understand this line, but I'll try to explain it as good as I can. We use a for loop and 10 times we use "random.choice" to select a letter from the letters variable. To create a string from the letters we are choosing, we use ""join"" to join them together.

Creating a password

The last thing we need to do now is to print a password to the screen. Below the generatePassword function, add this line:

print( generatePassword() )

We use "print" to print the password to the screen. When we call the "generatePassword()" function, we get a password in return.

I hope you liked this little guide. There is a lot of different things you can add to the code to make it more dynamically like adding a optional length limit, choose which characters to use and so on. If you got any questions about this guide, feel free to leave a reply below!

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.