What you end up with
password.py the script file, 15 lines
python password.py running it
Password: oo_-MiEWL9B2xvoBu8_K
PIN: 693181
Every run gives a new password. It’s made of Latin letters, digits, - and _: any site or router accepts these, and
they need no escaping on the command line.
Step by step
Create the file
Make a folder for this set’s scripts, say
D:\scripts, and a file calledpassword.pyin it. Any editor that shows plain text will do: VS Code, Notepad++, even Notepad. VS Code with the Python extension adds highlighting and hints.Write the script
import secrets def make_password(length): """A password of Latin letters, digits, "-" and "_".""" return secrets.token_urlsafe(length)[:length] def make_pin(digits): """A PIN: digits only, leading zeros kept.""" return str(secrets.randbelow(10**digits)).zfill(digits) print("Password:", make_password(20)) print("PIN: ", make_pin(6))The 4-space indent isn’t decoration: it’s how Python knows which lines are inside the function.
Run it
cd D:\scripts python password.py # Password: FP138stGjqWrmlhHzujQ # PIN: 726953Adapt it
Need a longer password — change the number in the call:
make_password(32). Several passwords at once — severalprintlines. The script saves nothing: the password lives only in the terminal window, and from there it goes into your password manager.
What’s new here
- A
.pyfile. Program text thatpythonruns top to bottom.python password.pyworks likepython -m http.serverfrom Files to your phone, only the code is yours. import. Loads a module: afterimport secrets, everything in it is available in the code —secrets.token_urlsafe,secrets.randbelow. Thesecretsmodule is in the standard library; nothing to install.- A function:
defandreturn.def make_password(length):creates a function with a name and a parameter; the indented lines are its body, andreturnhands back the result. The triple-quoted string right afterdefis a description, which the editor shows as a hint. - A variable.
lengthanddigitsare names for the values passed in the call: inmake_password(20),lengthis 20 inside the function. Details — Variables and types.
What the lines themselves do:
| Piece | What it does |
|---|---|
secrets.token_urlsafe(20) |
20 random bytes as text: 27 characters out of 64 possible |
[:length] |
the first length characters; slices are in Strings |
secrets.randbelow(10**6) |
a random number from 0 to 999,999; ** is a power |
str(…).zfill(6) |
the number as text, zero-padded on the left to 6 digits: 42 becomes 000042 |
Why secrets and not random
random gives numbers that look random but are computed from a starting value: knowing a few outputs, you can predict
the rest. The documentation says outright that it’s not for passwords and tokens. secrets takes its randomness from
the operating system — the source encryption software uses for keys.
What a password is worth: each character out of 64 is 6 bits, 20 characters are 120 bits, 2¹²⁰ combinations. A 6-digit PIN is about 20 bits, a million combinations: it only works where three wrong tries lock you out, as with a SIM card.
If it doesn’t work
python: can't open file '…\password.py': [Errno 2] No such file or directory
- Cause
- The terminal is open in another folder:
pythonlooks for the file where you are now. - Fix
cdinto the script’s folder, or use the full path:python D:\scripts\password.py.
NameError: name 'secrets' is not defined. Did you forget to import 'secrets'?
- Cause
- There’s no
import secretsline at the top of the file, or it has a typo. - Fix
- Make
import secretsthe first line; the module name and the name in the code must match letter for letter.
IndentationError: expected an indented block after function definition
- Cause
- The lines inside the
defaren’t indented: Python uses indentation to tell what belongs to the function. - Fix
- Indent the function body 4 spaces; an editor with Python highlighting does it after
:on its own.
AttributeError: module 'secrets' has no attribute 'token_urlsafe' (consider renaming '…\secrets.py' …)
- Cause
- The script’s folder has your own
secrets.py, andimport secretsfound it before the standard library module. Python 3.15 points out which file is in the way. - Fix
- Rename your file — to
password.py. Don’t name your files after modules:secrets,random,string.
How to check
Run python password.py twice in a row — the passwords differ, each is 20 characters long, and the PIN is 6 digits,
including when it starts with a zero.