To generate random numbers in Python, you use the built-in random module. The most common function is random.random(), which returns a float between 0.0 and 1.0, but you’ll often want integers, choices from a list, or numbers with a specific distribution. This guide walks you through the essential functions, with clear examples, so you can start using randomness in your scripts right away.
What You’ll Need
- Python 3.x installed (any recent version works; the examples use Python 3.10+).
- A text editor or IDE (like VS Code, PyCharm, or IDLE).
- Basic familiarity with running Python scripts from the command line or your editor.
Step-by-Step
- Import the random module. At the top of your script, add
import random. This gives you access to all the random functions. If you only need a few, you can also dofrom random import randint, choice, but importing the whole module is simplest and avoids name conflicts. - Generate a random float between 0 and 1. Use
random.random(). This returns a float like0.3745401188473625. It’s the foundation for many other random operations. - Generate a random integer in a range. Use
random.randint(a, b)to get an integer betweenaandb, inclusive. For example,random.randint(1, 10)gives you a number from 1 to 10. If you want to step by a specific amount, userandom.randrange(start, stop, step)instead — note thatstopis exclusive. - Pick a random element from a list. Use
random.choice(sequence). For instance,random.choice(['red', 'green', 'blue'])returns one of those colors. To get multiple unique items, userandom.sample(sequence, k), wherekis how many you want. For duplicates allowed, userandom.choices(sequence, k=k). - Shuffle a list in place. Call
random.shuffle(my_list). This rearranges the list randomly. It modifies the original list and returnsNone, so don’t try to assign the result. - Generate a random float in a specific range. Use
random.uniform(a, b)to get a float betweenaandb, inclusive of both ends approximately. For example,random.uniform(5.5, 9.5)returns a float like7.234.... - Set a seed for reproducibility. Call
random.seed(42)before generating numbers. This makes the sequence of random numbers deterministic — you’ll get the same numbers every time you run the script. This is crucial for testing and debugging. - Generate a random boolean (True/False). Use
random.choice([True, False])orrandom.random() < 0.5. The latter gives a 50% chance of True, but you can adjust the threshold for different probabilities. - Use the secrets module for security-sensitive randomness. For passwords, tokens, or anything cryptographic, use
secretsinstead ofrandom. For example,secrets.randbelow(100)gives a secure random integer below 100. Therandommodule is not cryptographically secure.
Common Mistakes
- Forgetting to import random. You'll get a
NameErrorif you try to userandomwithout importing it. - Using
randintwith the stop value exclusive. Unlikerange(),randintincludes both endpoints. Many beginners expectrandint(1, 10)to exclude 10, but it includes it. - Confusing
samplewithchoices.sampledoes not allow duplicates (unless the sequence has duplicates), whilechoicesdoes. If you need repeated picks, usechoices. - Assigning the result of
shuffle.shufflereturnsNone; it modifies the list in place. Assigning it to a variable gives youNone. - Using
randomfor security. Therandommodule is predictable if an attacker knows the seed or the state. Always usesecretsfor passwords or tokens.
Tips
- Seed once at the start. If you set the seed inside a loop, you'll get the same number every iteration. Set it once before the loop.
- Use
random.choiceswith weights. You can assign probabilities:random.choices(['low', 'mid', 'high'], weights=[0.2, 0.3, 0.5], k=10)gives a weighted random selection. - For many numbers, use list comprehensions. For example,
[random.randint(1, 100) for _ in range(20)]creates a list of 20 random ints. - Check the Python docs. The
randommodule has many more functions likegauss,expovariate, andlognormvariatefor statistical distributions. - Test with a fixed seed. When debugging, set
random.seed(0)at the top of your script so you can reproduce the exact same random sequence and trace errors.
Troubleshooting
- NameError: name 'random' is not defined. You forgot to import it. Add
import randomat the top. - ValueError: sample larger than population. You asked for more items than the sequence has. Reduce the
kvalue or add more elements to the sequence. - TypeError: 'NoneType' object is not iterable. This happens when you try to iterate over the result of
shuffle(). Remember,shufflereturnsNone; use the original list. - Random numbers are the same each run. You likely have a seed set. If you don't want deterministic behavior, remove the
seed()call. - Numbers are not uniform. If you're using
random.random()and multiplying, you might get a slight bias. For a uniform range, userandom.uniform(a, b)directly. - ImportError: No module named 'random'. This is extremely rare; it usually means your Python environment is corrupted. Reinstall Python or check your PATH.
Frequently Asked Questions
- How do I generate a random integer between 1 and 100? Use
random.randint(1, 100). It includes both 1 and 100. - What's the difference between
randintandrandrange?randint(a, b)is inclusive of both endpoints.randrange(a, b)is exclusive ofb, and you can specify a step. For example,randrange(0, 10, 2)gives even numbers from 0 to 8. - Can I generate a random float between 0 and 1? Yes,
random.random()does exactly that. For a different range, userandom.uniform(a, b). - How do I make my random numbers reproducible? Call
random.seed(42)(or any integer) before generating numbers. This ensures the same sequence each run. - Is the
randommodule safe for passwords? No, it's not cryptographically secure. Use thesecretsmodule for passwords, tokens, or any security-sensitive data. - How do I pick a random item from a dictionary? You can use
random.choice(list(my_dict.keys()))to pick a random key, orrandom.choice(list(my_dict.values()))for a value.
Related
- Google Sheets HEX2DEC Function Explained
- Google Sheets Sum If Checkbox Is Checked
- Generate 8 Random Numbers: How to Do It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Split Sheet Set: Meaning, Sizes, and How to ChooseA split sheet set is bedding designed for a bed whose sleeping surface is divided into separate sections,…
- Open Excel for the Web in the Desktop AppTo open an Excel for the web workbook in the desktop app, choose Open in Desktop App near…
- Schedule an Email in Outlook Desktop: Step-by-StepTo schedule an email in Outlook desktop, compose your message and choose a future send time: in new…
- Split String SQL Server: Best MethodsTo split a string in SQL Server, the best method is to use the built-in STRING_SPLIT function (available…
- Balance GraphQL Checklist for Accurate API DesignA balance GraphQL checklist is a practical set of checks for making balance data precise, permission-controlled, consistent, and…
- Google Sheets Conditional Formatting: How to Add RulesTo add conditional formatting in Google Sheets, select the cells, choose Format > Conditional formatting, set a condition…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.