Func Number Random
## Python random() Function
The `random()` method is a built-in function from Python's standard `random` module. It is used to generate a random floating-point number in the range $[0.0, 1.0)$.
This tutorial covers the syntax, parameters, return values, and practical use cases of the `random()` function.
---
## Description
The `random()` method returns a randomly generated real number (float) that is greater than or equal to `0.0` and strictly less than `1.0`. Mathematically, this is represented as the half-open interval $[0.0, 1.0)$.
---
## Syntax
To use the `random()` method, you must first import the `random` module. You cannot call the function directly without importing the module.
```python
import random
random.random()
```
> **Note:** `random()` is a method of the `random` module's shared instance. It is accessed as a static-like method via the imported `random` namespace.
---
## Parameters
* **None** β This method does not accept any arguments.
---
## Return Value
* Returns a **float** value in the range `[0.0, 1.0)`.
---
## Code Examples
### Basic Usage
The following example demonstrates how to import the `random` module and generate random floating-point numbers.
```python
#!/usr/bin/python3
import random
# Generate the first random float
print("First random number : ", random.random())
# Generate the second random float
print("Second random number: ", random.random())
```
**Example Output:**
```text
First random number : 0.281954791393
Second random number: 0.309090465205
```
*(Note: The actual output will vary each time you run the script.)*
---
## Advanced Considerations & Common Use Cases
While `random.random()` only generates numbers between `0` and `1`, you can easily scale and shift the output to fit other ranges.
### 1. Generating a Random Float in a Custom Range $[a, b)$
To generate a random float between a custom range $[a, b)$, you can use the formula:
$$\text{value} = a + (b - a) \times \text{random.random()}$$
```python
import random
# Generate a random float between 5.0 and 10.0
low = 5.0
high = 10.0
scaled_random = low + (high - low) * random.random()
print("Random float between 5.0 and 10.0:", scaled_random)
```
*(Note: Python also provides `random.uniform(a, b)` as a built-in shorthand for this operation).*
### 2. Pseudo-Randomness Warning
The `random` module in Python uses the **Mersenne Twister** algorithm as its core generator. While it is excellent for simulations, modeling, and general programming, it is **not cryptographically secure**.
* **Security Warning:** Do not use `random.random()` for security-sensitive applications, such as generating passwords, security tokens, or cryptographic keys. For cryptographically secure random numbers, use Python's `secrets` module instead.
YouTip