How to Generate Random Number in Python: Simple Guide
To generate a random number in Python, use the
random module. For example, random.randint(a, b) returns a random integer between a and b inclusive.Syntax
The random module provides functions to generate random numbers. The most common function is random.randint(a, b), which returns a random integer between a and b inclusive.
Other useful functions include random.random() for a random float between 0 and 1, and random.uniform(a, b) for a random float between a and b.
python
import random # Generate a random integer between 1 and 10 print(random.randint(1, 10)) # Generate a random float between 0 and 1 print(random.random()) # Generate a random float between 1.5 and 5.5 print(random.uniform(1.5, 5.5))
Example
This example shows how to generate a random integer between 1 and 100 and print it.
python
import random random_number = random.randint(1, 100) print(f"Random number between 1 and 100: {random_number}")
Output
Random number between 1 and 100: 42
Common Pitfalls
- Forgetting to import the
randommodule before using its functions. - Using
random.randint(a, b)withagreater thanbcauses an error. - Expecting
random.random()to return integers; it returns floats between 0 and 1.
python
import random # Wrong: a is greater than b # random.randint(10, 5) # This will raise ValueError # Right: print(random.randint(5, 10))
Output
7
Quick Reference
| Function | Description | Example |
|---|---|---|
| random.randint(a, b) | Returns random integer between a and b inclusive | random.randint(1, 10) |
| random.random() | Returns random float between 0.0 and 1.0 | random.random() |
| random.uniform(a, b) | Returns random float between a and b | random.uniform(1.5, 5.5) |
Key Takeaways
Always import the random module before generating random numbers.
Use random.randint(a, b) to get a random integer between a and b inclusive.
random.random() returns a float between 0 and 1, not an integer.
Ensure the first argument is less than or equal to the second in randint to avoid errors.
Use random.uniform(a, b) for random floats within a range.