🎓 A1Learner
🔍
0 of 52 lessons completed

Python Project: A Password Generator

A password generator builds a password from random picks. It joins the picked characters into one string.

Pick three letters

choice() picks one letter per call. The same seed picks the same letters.

import random
random.seed(11)
letters = "abcdef"
print(random.choice(letters))
print(random.choice(letters))
print(random.choice(letters))

Glue parts into one string

join() glues a list into one string. The empty string adds nothing between the parts.

parts = ["a", "B", "3", "!"]
print("".join(parts))

Mix the characters

shuffle() mixes the characters. join() then glues the mixed list.

import random
random.seed(11)
chars = ["a", "b", "c", "d", "e"]
random.shuffle(chars)
print("".join(chars))

Example

import random
random.seed(42)
letters = "abcdefghijklmnopqrstuvwxyz"
digits = "23456789"
symbols = "!#?"
password = ""
for i in range(8):
    password = password + random.choice(letters)
password = password + random.choice(digits)
password = password + random.choice(symbols)
print(password)

Key points

  • Use random.choice(letters) to pick one character at a time
  • A loop picks one character per turn, so eight turns give eight characters
  • Use "".join(parts) to glue a list of characters into one string
  • Use random.seed(n) to fix the password, so the same run repeats
  • Mix letters, digits, and symbols for a stronger password

In this example, the seed is 42, so the password stays fixed. The loop picks eight letters, one per turn. A digit and a symbol join the letters at the end. The printout shows the ten-character password.

Note

The seed stays here so the output can be checked, and a real generator drops it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does "".join(["a", "B", "3"]) give back?