To generate a random number in Python, use the random module’s randint(), random(), or uniform() functions. For example, random.randint(1, 10) returns an integer between 1 and 10 inclusive. This guide covers the essential functions, step-by-step examples, common pitfalls, and troubleshooting.
What You’ll Need
- Python installed (version 3.x recommended; works with 2.7 but with minor differences).
- A text editor or IDE (like VS Code, PyCharm, or IDLE).
- Basic familiarity with running Python scripts from the command line or an IDE.
Step-by-Step
- Open your Python environment. Launch a Python interpreter (type
pythonin a terminal) or create a new script file (e.g.,random_demo.py). - Import the random module. At the top of your script, add
import random. This gives you access to all random functions. - Generate a random integer between two bounds. Use
random.randint(a, b)to get an integer N such thata <= N <= b. Example:print(random.randint(1, 100))prints a whole number from 1 to 100. - Generate a random floating-point number between 0 and 1. Use
random.random()which returns a float in [0.0, 1.0). Example:print(random.random()). - Generate a random float within a specific range. Use
random.uniform(a, b)to get a float between a and b (inclusive of both, but due to rounding, may not include b exactly). Example:print(random.uniform(5.5, 10.5)). - Generate a random element from a list. Use
random.choice(sequence)to pick a random item. Example:items = ['apple', 'banana', 'cherry']; print(random.choice(items)). - Generate a random sample without replacement. Use
random.sample(population, k)to get k unique items. Example:print(random.sample(range(1, 50), 5))gives 5 distinct integers from 1 to 49. - Shuffle a list randomly. Use
random.shuffle(list)to reorder the list in place. Example:cards = [1,2,3,4,5]; random.shuffle(cards); print(cards). - Set a seed for reproducibility (optional). Call
random.seed(42)before generating numbers to get the same sequence every run. This is useful for testing. - Run your script. Execute it and observe the output. Each run (without a seed) gives different results.
Common Mistakes
- Forgetting to import random. Using
randint()withoutimport randomraises aNameError. - Using
random.randint(1, 10.5)with a float.randintrequires integers; useuniformfor floats. - Assuming
random.random()returns an integer. It returns a float between 0 and 1; to get an integer, multiply and cast, e.g.,int(random.random() * 100). - Using
random.shuffle()on a tuple. Tuples are immutable; shuffle works only on lists. - Expecting
random.sample()to allow duplicates. It samples without replacement; if you need duplicates, userandom.choices().
Tips
- For cryptographic security (e.g., passwords), use
secretsmodule instead:secrets.randbelow(100). - To get a random integer from 0 to N-1, use
random.randrange(N). - Seed with a different value each run if you want non-reproducible results; the default is based on system time.
- Use
random.choices(population, weights=None, k=1)to pick items with replacement or with weights. - If you need many random numbers, consider using
numpy.randomfor performance, but that requires installing NumPy.
Troubleshooting
- I get a
NameError: name 'random' is not defined. Ensure you haveimport randomat the top of your script. - I get a
TypeError: randint() takes exactly 3 arguments (2 given). You are callingrandom.randint()as a method; it should berandom.randint(a, b)with the module prefix. - My random numbers are the same every time. You likely set a seed. To get different numbers, either remove the seed or use a different seed value.
- I get a
ValueError: empty range for randrange(). This happens whena > binrandint(a, b)or when usingrandrangewith start > stop. Check your bounds. - I want a random float but get an integer. Use
random.uniform()instead ofrandint(). - My list is not shuffled. Remember
shuffle()modifies the list in place and returnsNone. Print the list after calling it.
Frequently Asked Questions
How do I generate a random number between 1 and 100?
Use random.randint(1, 100) for an integer, or random.uniform(1, 100) for a float.
Can I generate a random number from a normal distribution?
Yes, use random.gauss(mu, sigma) or random.normalvariate(mu, sigma) for a normal distribution with mean mu and standard deviation sigma.
How do I generate a random boolean (True/False)?
Use random.choice([True, False]) or random.random() < 0.5 for a 50% chance.
Is random.randint() inclusive of both endpoints?
Yes, randint(a, b) returns an integer N such that a <= N <= b. For exclusive upper bound, use random.randrange(a, b).
How do I generate a random string?
Combine random.choice with a string of characters. For example: ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=5)).
Why does my random number change every time I run the script?
Because Python seeds the random generator with the current system time by default. To make it repeatable, use random.seed(42).
Related
- Data Entry Software for Small Surveys? Best Picks
- SQL Interview Queries for Experienced Developers
- Diagram of a 3 Cell Battery: Wiring & Layout
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets vs Excel: Which Spreadsheet Fits?Google Sheets is usually the better fit for browser-based collaboration and simple shared workflows; Microsoft Excel is generally…
- Compare Two Open Documents in Word: A Step-by-Step GuideTo compare two open documents in Microsoft Word, save both files, then choose Review > Compare > Compare…
- How to Insert a Checkbox in Word With a TickTo put a tick in a Word checkbox, insert a checked-box symbol for a fixed mark, or add…
- Microsoft Excel Password Protection: How It WorksYes. In Microsoft Excel for Microsoft 365 on Windows, you can encrypt a workbook with a password from…
- Sunday Service in Google Sheets: Planning and SchedulingYes. Google Sheets can serve as a shared planning sheet for a Sunday church service: use it to…
- Excel Time Format Over 24 Hours: Display Elapsed Time CorrectlyTo display a duration longer than 24 hours in Excel, select the cells, open Format Cells, choose Custom,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.