How to Produce Random Numbers in Python

How-to basics · Updated November 23, 2026

Python’s standard library gives you several ways to generate random numbers, from simple integers and floats to secure cryptographic values. The quickest method is using the random module: random.randint(1, 10) returns a random integer between 1 and 10 inclusive. This guide walks you through the core functions, how to choose the right one, and common pitfalls to avoid.

What You’ll Need

  • Python 3 installed (any recent version works; the examples use Python 3.10+).
  • A text editor or IDE (like VS Code, PyCharm, or IDLE).
  • No extra packages required — everything uses the built-in random and secrets modules.

Step-by-Step

  1. Import the random module. At the top of your script, add import random. This gives you access to all the basic random functions.
  2. Generate a random integer in a range. Use random.randint(a, b) to get an integer N such that a <= N <= b. For example, random.randint(1, 6) simulates a die roll.
  3. Get a random integer with a step (like even numbers). Use random.randrange(start, stop, step). For instance, random.randrange(0, 101, 2) gives a random even number from 0 to 100. Note that stop is exclusive.
  4. Generate a random float between 0 and 1. Call random.random() — it returns a float like 0.374. For a float in a custom range, use random.uniform(a, b), which returns a float between a and b inclusive (approximately).
  5. Pick a random item from a sequence. Use random.choice(sequence) where the sequence can be a list, tuple, or string. Example: random.choice(['heads', 'tails']).
  6. Get multiple unique items (sampling without replacement). Use random.sample(population, k) to get a list of k unique elements. For example, random.sample(range(100), 5) returns 5 distinct numbers from 0 to 99.
  7. Shuffle a list in place. Call random.shuffle(my_list). This modifies the original list; if you need a new list, copy it first with my_list.copy().
  8. Seed the generator for reproducibility. Call random.seed(42) before generating numbers. This makes the sequence repeatable, which is useful for debugging or simulations.
  9. For security-sensitive randomness, use the secrets module. Import secrets and use secrets.randbelow(n) for a secure integer from 0 to n-1, or secrets.choice(sequence) for a secure pick. This is essential for passwords, tokens, or anything that must be unpredictable.
  10. Generate a random boolean. Use random.choice([True, False]) or random.random() < 0.5 for a 50/50 chance.

Common Mistakes

  • Using random.randint() when you need floats. Remember, randint only returns integers.
  • Forgetting that randrange() excludes the stop value. random.randrange(1, 10) gives 1–9, not 10.
  • Using random.sample() with a population smaller than k. This raises a ValueError. Ensure the population has at least k items.
  • Modifying a list with shuffle() when you meant to keep the original. Always copy the list first if you need the original order.
  • Using random for security-critical data. The random module is not cryptographically secure; use secrets instead.
  • Setting the seed after generating numbers. The seed must be set before any random calls to have an effect.

Tips

  • For reproducible experiments, set a seed at the start of your script: random.seed(123). This is great for testing.
  • To get a random float in a specific range, random.uniform(a, b) is clearer than doing a + (b-a)*random.random().
  • If you need many random numbers, consider using list comprehensions: [random.randint(1, 100) for _ in range(10)] gives a list of 10 random integers.
  • For a random element from a dictionary, convert keys or values to a list first: random.choice(list(my_dict.keys())).
  • Use random.choices() with weights to get weighted random selections, e.g., random.choices(['red', 'blue'], weights=[3, 1], k=5).

Troubleshooting

  • You get the same numbers every run. This happens if you set a seed. Remove the random.seed() call, or move it to a different value if you want reproducibility.
  • You get a ValueError: sample larger than population. Check that your k value in random.sample() does not exceed the length of the population. Reduce k or use random.choices() if duplicates are allowed.
  • Your random numbers look non-random (e.g., all even). This is usually a misunderstanding of the range or step. Double-check your randrange arguments and ensure you’re not accidentally using a fixed step.
  • You get a TypeError when using randint. Make sure both arguments are integers. If you have floats, convert them with int() first.
  • You need randomness but the module is not found. Ensure you typed import random correctly and that your file is not named random.py, which would shadow the built-in module.

Frequently Asked Questions

  • What is the difference between random.randint() and random.randrange()? randint(a, b) includes both endpoints, while randrange(start, stop, step) excludes the stop value. For example, randint(1, 3) can return 1, 2, or 3, but randrange(1, 3) returns only 1 or 2.
  • Can I generate a random number between 0 and 1 with more than 15 decimal places? Python’s floats have about 15–17 significant digits, so you cannot get more precision than that. For arbitrary precision, you’d need the decimal module or other libraries.
  • How do I generate a random password? Use the secrets module: import secrets, then secrets.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') repeated, or use secrets.token_bytes() for raw bytes.
  • Why should I use secrets instead of random for security? The random module uses a deterministic pseudo-random number generator that is predictable if the seed is known. The secrets module uses OS-provided sources of entropy, making it unpredictable and suitable for security-sensitive tasks.
  • How do I make my random numbers reproducible across different runs? Call random.seed(some_integer) at the start of your script. As long as you use the same seed, you’ll get the same sequence of numbers.
  • Can I generate a random number from a normal distribution? Yes, use random.gauss(mu, sigma) or random.normalvariate(mu, sigma) to get a float from a normal distribution with mean mu and standard deviation sigma.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.