×

python · level 3 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Use , not random, for anything that must stay secret.

random is built for games and simulations. Its numbers follow a hidden pattern, so with enough samples an attacker can predict the next one. Never use it for a password, a or a sign-in code.

The secrets module asks the operating system for values nobody can predict. token_hex(16) gives 32 characters from 0 to 9 and a to f, token_urlsafe(16) gives a token safe to put in a link, and choice picks from a list.

Check a secret with secrets.compare_digest(a, b). A plain == stops at the first wrong character, so its speed can leak how much of a guess was right. That is a .

import secrets
import string

reset_token = secrets.token_urlsafe(16)
print("Reset link: https://example.com/reset?token=" + reset_token)
alphabet = string.ascii_uppercase + string.digits
code = "".join(secrets.choice(alphabet) for n in range(6))
print("Your sign-in code is", code)
print(secrets.compare_digest(code, code))

Your output differs from everyone else's, and from your own next run, which is the whole point.