Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Random Number: Easy How-To Example

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To create a random number in Python, import the random module and call one of its functions: random.randint(1, 10) gives a whole number between 1 and 10 inclusive, random.random() gives a float from 0.0 up to but not including 1.0, and random.choice(['a','b','c']) picks a random item from a list. That is the shortest working answer. The steps below cover the common cases, how to make results reproducible with a seed, and how to avoid the mistakes that trip people up.

What You'll Need

  • A working Python installation (version 3.6 or later is fine for everything here). You can check by running python --version or python3 --version in a terminal.
  • A way to run Python code: the interactive interpreter (type python or python3), a script file saved as .py, or an editor such as IDLE, VS Code, or any IDE you already use.
  • No extra packages. The random module is part of the Python standard library, so there is nothing to install with pip.

Step-by-Step

  1. Import the module. At the top of your script or in the interpreter, type import random. This loads the standard library module that contains all the random-number functions. If you see ModuleNotFoundError: No module named 'random', you are almost certainly running a different language or a broken Python install; random ships with Python, so reinstall Python from python.org rather than trying to pip install it.
  2. Pick the right function for your number type. Use random.randint(a, b) when you need a whole number and want both endpoints included. Use random.randrange(start, stop, step) when you want a whole number but want the stop value excluded, or want a step (for example even numbers only). Use random.random() for a float between 0.0 and 1.0, and random.uniform(a, b) for a float in a custom range. Use random.choice(sequence) to pick one element from a list, tuple, or string. Use random.shuffle(list) to reorder a list in place, and random.sample(population, k) to pick k unique items without replacement.
  3. Write a first example. In a file called dice.py, put:
    import random
    roll = random.randint(1, 6)
    print(roll)
    Run it with python dice.py. Each run prints a number from 1 to 6. Because randint includes both ends, 1 and 6 are both possible; if you used randrange(1, 6) instead, 6 would never appear. That off-by-one difference is the most common source of bugs in random-number code.
  4. Generate several numbers at once. To roll five dice, use a loop or a list comprehension: rolls = [random.randint(1, 6) for _ in range(5)]. For a float in a range, random.uniform(1.5, 2.5) returns a value between those bounds. For a random choice from a list, random.choice(['red', 'green', 'blue']) returns one string.
  5. Make results reproducible with a seed. Call random.seed(42) once before generating numbers, and the sequence of results will be the same every time you run the script. This is essential for debugging and for tests where you need predictable output. Change the seed number to get a different but still repeatable sequence. Do not seed with the current time or with random.random() unless you specifically want a different sequence each run; Python already seeds itself from the operating system when the module is imported.
  6. Use the right tool for security-sensitive randomness. The random module is a pseudo-random number generator: it is fine for games, simulations, sampling, and test data, but it is not suitable for passwords, tokens, encryption keys, or anything an attacker could predict. For those, use the secrets module, also in the standard library. For example, import secrets then secrets.randbelow(10) gives a secure random integer from 0 to 9, and secrets.choice('abcdef0123456789') picks a secure random character. For cryptographic keys, use secrets.token_bytes(32) or secrets.token_hex(16).
  7. Test the output range. After writing your code, run a quick sanity check: generate a thousand numbers and confirm the minimum and maximum fall inside the expected bounds. For example, nums = [random.randint(1, 10) for _ in range(1000)] then print(min(nums), max(nums)). If you see a value outside 1 to 10, you have used the wrong function or swapped the arguments.

Common Mistakes

  • Confusing randint and randrange. randint(1, 6) can return 6; randrange(1, 6) cannot. Pick deliberately and document which behaviour you want.
  • Calling random.random without parentheses. That gives you the function object, not a number. Always call it: random.random().
  • Seeding inside a loop. Calling random.seed() repeatedly resets the generator and can produce repeated or predictable values. Seed once, at the start.
  • Using random for passwords or tokens. It is predictable by design. Use secrets instead.
  • Assuming random.shuffle returns a new list. It shuffles in place and returns None. If you need the original order preserved, copy the list first with list(original).
  • Passing floats to randint. It expects integers. For a float range, use uniform.

Tips

  • Use random.choices(population, k=n) (with an s) when you want n picks and repeats are allowed; use random.sample(population, k=n) when repeats are not allowed.
  • For weighted choices, random.choices(items, weights=[3, 1, 1], k=1) makes the first item three times as likely.
  • Keep a fixed seed in unit tests so failures are reproducible, and a random seed in production so results vary.
  • If you need the same random sequence across different machines or Python versions, note that the algorithm behind random is stable within a Python version but not guaranteed across major versions. For cross-version reproducibility, use random.Random(seed) with an explicit seed and test on your target versions.
  • When generating a random integer for a game or simulation, prefer randrange or randint over converting a float, because float conversion can introduce off-by-one errors at the boundaries.

Troubleshooting

If your script prints the same number every time, check whether you have called random.seed() with a fixed value. That is expected behaviour with a seed; remove the seed call or change the seed to get different results. If you get an AttributeError such as module 'random' has no attribute 'randint', you may have named your own file random.py, which shadows the standard library module. Rename your file and delete any random.pyc cache, then run again. If import random fails with a ModuleNotFoundError, confirm you are running Python (not another language) and that your installation is intact; reinstall Python from the official source if needed. If numbers seem biased or repeat too often, check that you are not reseeding inside a loop and that you are using the correct range. For security-sensitive code, switch from random to secrets and re-test.

Frequently Asked Questions

How do I get a random number between 1 and 10 in Python?

Use random.randint(1, 10). Both 1 and 10 are possible. If you want 10 excluded, use random.randrange(1, 10).

What is the difference between random.random() and random.uniform()?

random.random() always returns a float from 0.0 up to but not including 1.0. random.uniform(a, b) returns a float between a and b, and the bounds can be any numbers, including negatives.

Can I generate a random number without importing anything?

No. Python's built-in functions do not include a random-number generator. You must import random (or secrets for secure values) from the standard library.

How do I make Python's random numbers reproducible?

Call random.seed(some_number) once before generating values. The same seed produces the same sequence on the same Python version. Use a different seed or omit the call to get different results each run.

Is Python's random module safe for passwords?

No. It is a pseudo-random generator and is not cryptographically secure. Use the secrets module for passwords, tokens, and keys.

Why does random.shuffle() return None?

It shuffles the list in place and returns nothing. If you need a shuffled copy, do shuffled = list(original); random.shuffle(shuffled).