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
randomandsecretsmodules.
Step-by-Step
- Import the random module. At the top of your script, add
import random. This gives you access to all the basic random functions. - Generate a random integer in a range. Use
random.randint(a, b)to get an integer N such thata <= N <= b. For example,random.randint(1, 6)simulates a die roll. - 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 thatstopis exclusive. - 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, userandom.uniform(a, b), which returns a float betweenaandbinclusive (approximately). - 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']). - Get multiple unique items (sampling without replacement). Use
random.sample(population, k)to get a list ofkunique elements. For example,random.sample(range(100), 5)returns 5 distinct numbers from 0 to 99. - Shuffle a list in place. Call
random.shuffle(my_list). This modifies the original list; if you need a new list, copy it first withmy_list.copy(). - Seed the generator for reproducibility. Call
random.seed(42)before generating numbers. This makes the sequence repeatable, which is useful for debugging or simulations. - For security-sensitive randomness, use the secrets module. Import
secretsand usesecrets.randbelow(n)for a secure integer from 0 to n-1, orsecrets.choice(sequence)for a secure pick. This is essential for passwords, tokens, or anything that must be unpredictable. - Generate a random boolean. Use
random.choice([True, False])orrandom.random() < 0.5for a 50/50 chance.
Common Mistakes
- Using
random.randint()when you need floats. Remember,randintonly 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 aValueError. 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
randomfor security-critical data. Therandommodule is not cryptographically secure; usesecretsinstead. - 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 doinga + (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 yourkvalue inrandom.sample()does not exceed the length of the population. Reducekor userandom.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
randrangearguments and ensure you’re not accidentally using a fixed step. - You get a
TypeErrorwhen usingrandint. Make sure both arguments are integers. If you have floats, convert them withint()first. - You need randomness but the module is not found. Ensure you typed
import randomcorrectly and that your file is not namedrandom.py, which would shadow the built-in module.
Frequently Asked Questions
- What is the difference between
random.randint()andrandom.randrange()?randint(a, b)includes both endpoints, whilerandrange(start, stop, step)excludes the stop value. For example,randint(1, 3)can return 1, 2, or 3, butrandrange(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
decimalmodule or other libraries. - How do I generate a random password? Use the
secretsmodule:import secrets, thensecrets.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')repeated, or usesecrets.token_bytes()for raw bytes. - Why should I use
secretsinstead ofrandomfor security? Therandommodule uses a deterministic pseudo-random number generator that is predictable if the seed is known. Thesecretsmodule 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)orrandom.normalvariate(mu, sigma)to get a float from a normal distribution with meanmuand standard deviationsigma.
Related
- IMCOSH in Google Sheets: Formula & Examples
- Experience with Data Entry? What It Really Involves
- Python Generate N Random Numbers: 4 Easy Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel to HTML Table: Export, Format, and Embed DataTo convert Excel data to an HTML table in Microsoft 365 for Windows, select the cells if you…
- Excel Meal Prep Template: Plan Meals, Shop SmarterYes. An Excel meal-prep template can combine a weekly meal plan, recipe quantities, and a grocery list in…
- Excel Ran Out of Resources: Causes and FixesWhen Excel says it ran out of resources, it could not get enough memory or another system resource…
- Excel Split Cell Data Into Multiple ColumnsTo split cell data into separate columns in Excel for Microsoft 365 on Windows, select the cells, choose…
- Linear Programming Excel Solver Template: Build and Use OneA linear programming Excel Solver template is a worksheet with decision-variable cells, formulas for the objective and resource…
- Keyboard Shortcut to Ungroup in Excel (Windows & Mac)In Excel for Microsoft 365 on Windows, select the grouped rows or columns and press Alt+Shift+Left Arrow to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.