basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    A 120-bit password from your own script: the first .py file and the secrets module

    Write your first .py file: two functions that produce a 20-character password and a PIN. The randomness comes from the secrets module — made for passwords and keys, unlike random. 20 characters out of 64 is 120 bits: no brute force will guess such a password.

    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

    1. Create the file

      Make a folder for this set’s scripts, say D:\scripts, and a file called password.py in it. Any editor that shows plain text will do: VS Code, Notepad++, even Notepad. VS Code with the Python extension adds highlighting and hints.

    2. 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.

    3. Run it

      cd D:\scripts
      python password.py
      # Password: FP138stGjqWrmlhHzujQ
      # PIN:      726953
    4. Adapt it

      Need a longer password — change the number in the call: make_password(32). Several passwords at once — several print lines. 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 .py file. Program text that python runs top to bottom. python password.py works like python -m http.server from Files to your phone, only the code is yours.
    • import. Loads a module: after import secrets, everything in it is available in the code — secrets.token_urlsafe, secrets.randbelow. The secrets module is in the standard library; nothing to install.
    • A function: def and return. def make_password(length): creates a function with a name and a parameter; the indented lines are its body, and return hands back the result. The triple-quoted string right after def is a description, which the editor shows as a hint.
    • A variable. length and digits are names for the values passed in the call: in make_password(20), length is 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: python looks for the file where you are now.
    Fix
    cd into 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 secrets line at the top of the file, or it has a typo.
    Fix
    Make import secrets the 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 def aren’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, and import secrets found 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.