A Python project – A password generator
Lesson 3 of 15 · Python projects
In this project we will make a program that generates secure random passwords.
A password generator is a practical Python project because it uses working with text, random values and lists.
In this project we will use:
- the random module
- the string library
- working with text
- a loop for generating the password
How the password generator works
First the program asks the user how many characters the password should have.
Then Python randomly chooses characters from a set of letters, digits and special characters.
An example of the program running
How many characters should the password have? 10
Generated password: A7d#K2p!x9
The program code
import random
import string
length = int(input("How many characters should the password have? "))
characters = string.ascii_letters + string.digits + string.punctuation
password = ""
for i in range(length):
password += random.choice(characters)
print("Generated password:", password)
How this code works
- string.ascii_letters contains upper-case and lower-case letters
- string.digits contains the digits
- string.punctuation contains special characters
- random.choice() chooses a random character
Note: the
random module is fine for practice, but for real passwords Python recommends the secrets module: import secrets and secrets.choice(characters) instead of random.choice(characters).
You can extend the program by
adding an option for the user to choose whether
the password contains digits or special characters.
Possible improvements to the project
- add a choice of character types
- generate several passwords at once
- make a graphical version of the program
- save the password to a file
Next project
How to make the project your own:
1) first run the given code without changes, 2) change one thing and predict what will happen, 3) add at least one feature of your own, 4) write down in a notebook what you changed and why. A work log like that is the basis of a creative programming paper.
1) first run the given code without changes, 2) change one thing and predict what will happen, 3) add at least one feature of your own, 4) write down in a notebook what you changed and why. A work log like that is the basis of a creative programming paper.
