KAHIBARO Bookshelves
Discord Login Register

17.4. Password generator

What You’ll Build

In this mini project, you’ll create a Python program that generates random passwords for you.

By the end of this chapter, you will:

  • Decide what makes a “good” password
  • Design a simple password generator
  • Implement it step by step
  • Improve it with options (length, character types)
  • Add simple checks to avoid very weak passwords

We’ll focus on putting together things you already know: variables, strings, loops, if statements, and random numbers.


Planning the Password Generator

Before writing any code, decide what your program should do.

Basic requirements

Our first version will:

  1. Ask the user how long the password should be (number of characters)
  2. Generate a random password of that length
  3. Show the password to the user

We’ll start simple: letters (both lowercase and uppercase) and digits.

So a password might look like:

  • aX9pT3
  • L0ngPa55w0rd
  • mQ4z2H1x

Later, we’ll add:

  • Special characters like !@#$%&*?
  • Checks for minimum length
  • Options to choose what kinds of characters to include

Choosing Characters for the Password

A password is just a string made from a set of allowed characters.

Character sets

We can define some character sets as strings:

lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "!@#$%&*?"

To build our pool of possible characters, we can combine strings:

all_chars = lowercase + uppercase + digits

Now all_chars contains all the characters we might use in our password.

Example of what all_chars might look like:

"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"


Using `random` to Pick Characters

To build a password, we need to randomly pick characters from all_chars.

We’ll use the random module:

import random
all_chars = "abc123"
random_char = random.choice(all_chars)
print(random_char)  # could be 'a', 'b', 'c', '1', '2', or '3'

random.choice(some_string) picks one random character from that string.

To build a password of length n, we can:

  1. Start with an empty string: password = ""
  2. Repeat n times:
    • Pick a random character from all_chars
    • Add (+) it to password

First Version: Simple Password Generator

Let’s put this together into a small script.

Features:

  • Asks for password length
  • Generates a random password using letters and digits
  • Prints the result
import random
# 1. Define the characters we can use
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
all_chars = lowercase + uppercase + digits
# 2. Ask the user for the password length
length_text = input("How long should the password be? ")
length = int(length_text)
# 3. Build the password
password = ""
for _ in range(length):
    random_char = random.choice(all_chars)
    password += random_char
# 4. Show the password
print("Your password is:", password)

Try running this and generate a few passwords.


Handling Invalid Lengths

Your program will crash if the user types something that’s not a number, or gives a number that’s too small.

Let’s handle some simple cases:

  • If the user types a non-number → we’ll show a message and exit
  • If the length is less than a minimum (for example, 4) → we’ll warn and ask again or stop

To keep it simple, we’ll:

  • Use try/except for conversion errors
  • Check that the length is at least 4
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
all_chars = lowercase + uppercase + digits
length_text = input("How long should the password be? ")
try:
    length = int(length_text)
except ValueError:
    print("Please enter a valid number next time.")
    quit()
if length < 4:
    print("Password should be at least 4 characters long.")
    quit()
password = ""
for _ in range(length):
    password += random.choice(all_chars)
print("Your password is:", password)

Adding Special Characters (Symbols)

Many websites require special characters. Let’s add them as an option.

We’ll:

  1. Ask the user if they want to include symbols
  2. If they say yes, we add symbols to all_chars
  3. Otherwise, we keep using only letters and digits
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "!@#$%&*?"
# Ask user about password length
length_text = input("How long should the password be? ")
try:
    length = int(length_text)
except ValueError:
    print("Please enter a valid number next time.")
    quit()
if length < 4:
    print("Password should be at least 4 characters long.")
    quit()
# Ask whether to include symbols
use_symbols = input("Include symbols (!@#$%&*?)? (y/n): ")
all_chars = lowercase + uppercase + digits
if use_symbols.lower() == "y":
    all_chars += symbols
# Build the password
password = ""
for _ in range(length):
    password += random.choice(all_chars)
print("Your password is:", password)

Test it twice:

  • Once with y (symbols allowed)
  • Once with n (symbols not allowed)

Ensuring Password Has a Mix of Characters

The previous version can still create passwords that are not very strong, for example:

  • Only lowercase letters
  • Only digits

You might want to ensure that the password has at least:

  • One lowercase letter
  • One uppercase letter
  • One digit
  • (Optional) One symbol (if symbols are used)

Strategy

  1. Decide which character groups must be included
  2. Pick at least one character from each required group
  3. Fill the remaining characters randomly from the full pool
  4. Shuffle the final password so required characters aren’t always at the start

We’ll need another function from random: random.shuffle.

It works with lists, so we’ll:

  • Build the password as a list of characters
  • Shuffle the list
  • Join it into a string at the end

Stronger Password Generator Version

Here is an improved version that tries to include:

  • At least one lowercase
  • At least one uppercase
  • At least one digit
  • At least one symbol (if use_symbols == "y")
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "!@#$%&*?"
length_text = input("How long should the password be? ")
try:
    length = int(length_text)
except ValueError:
    print("Please enter a valid number next time.")
    quit()
if length < 4:
    print("Password should be at least 4 characters long.")
    quit()
use_symbols = input("Include symbols (!@#$%&*?)? (y/n): ")
# Collect the character groups we will use
char_groups = [lowercase, uppercase, digits]
if use_symbols.lower() == "y":
    char_groups.append(symbols)
# Build the pool of all possible characters
all_chars = ""
for group in char_groups:
    all_chars += group
# 1) Start by making sure we include at least one character from each group
password_chars = []
for group in char_groups:
    password_chars.append(random.choice(group))
# 2) Fill the rest of the password with random characters from the full pool
while len(password_chars) < length:
    password_chars.append(random.choice(all_chars))
# 3) Shuffle the characters so required ones are not always at the front
random.shuffle(password_chars)
# 4) Join the list into a string
password = "".join(password_chars)
print("Your strong password is:", password)

Try running this version multiple times and notice:

  • You always get at least one lowercase, one uppercase, and one digit
  • If you choose to include symbols, you always get at least one symbol
  • The order is random because of random.shuffle

Extra Ideas and Enhancements

Here are some ways you can extend this project.

1. Difficulty levels

Let the user choose a difficulty level:

  • 1 = only letters
  • 2 = letters and digits
  • 3 = letters, digits, and symbols

You could ask:

level = input("Choose level (1 = letters, 2 = letters+digits, 3 = strong): ")

Then build char_groups based on the level.

2. Generate multiple passwords at once

Ask the user how many passwords to generate, then use a loop to print several different passwords:

count_text = input("How many passwords do you want? ")
count = int(count_text)
for _ in range(count):
    # generate one password (reuse your existing logic)
    print("Password:", password)

(You’d move your password-creation logic into a function or inner block.)

3. Avoid confusing characters

Some characters look similar:

  • O and 0
  • l and 1

You can remove them from your character sets if you want more readable passwords.

Example: Use

uppercase = "ABCDEFGHJKLMNPQRSTUVWXYZ"  # no I or O
digits = "23456789"                    # no 0 or 1

4. Copying or saving passwords

For now, you’re just printing the password, but you could:

  • Save it to a text file (with a warning about security)
  • Display it in a nicer format (e.g., with labels like “Website: …, Password: …”)

Summary

In this mini project, you:

  • Planned what a password generator should do
  • Built a basic version using letters and digits
  • Handled user input and simple validation for length
  • Added options for symbols
  • Ensured the password contains a mix of character types
  • Used the random module (choice, shuffle) to create random passwords

This project is a good example of combining many Python basics into a practical tool. As practice, try adding one or two of the extra ideas and see how far you can customize your own password generator.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms