Kahibaro
Discord Login Register

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:

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:

Later, we’ll add:

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:

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:

To keep it simple, we’ll:

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:

Ensuring Password Has a Mix of Characters

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

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

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:

Stronger Password Generator Version

Here is an improved version that tries to include:

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:

Extra Ideas and Enhancements

Here are some ways you can extend this project.

1. Difficulty levels

Let the user choose a difficulty level:

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:

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:

Summary

In this mini project, you:

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: 15

Comments

Please login to add a comment.

Don't have an account? Register now!