Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Python's standard library includes comprehensive mathematical and stochastic computing capabilities out of the box. The math module provides access to C-standard mathematical functions for floating-point arithmetic, while the random module provides tools for generating pseudo-random numbers, shuffling datasets, and stochastic modeling.
math ModuleThe math module operates on real numbers (for complex numbers, Python provides cmath).
randomPython's random module uses the Mersenne Twister algorithm to produce deterministic pseudo-random sequences.
Setting a seed ensures identical random sequences across executions—vital for reproducible data science experiments and automated testing:
| Function | Behavior | Mutates Original? | Replacement? |
|---|---|---|---|
random.choice(seq) | Returns 1 random item | No | N/A |
random.choices(seq, k=n) | Returns $n$ items (can pick same item repeatedly) | No | With Replacement |
random.sample(seq, k=n) | Returns $n$ unique items (lottery draw) | No | Without Replacement |
random.shuffle(seq) | Rearranges elements in-place | Yes | In-place |
random module is NOT cryptographically secure! Never use random to generate passwords, authentication tokens, encryption keys, or password reset URLs.
For security-sensitive randomness, use Python's built-in secrets module:
```python
import secrets
secure_token = secrets.token_hex(16) # Safe for security tokens
```random for Passwords and Security TokensThe random module uses the Mersenne Twister algorithm, which is completely predictable and cryptographically insecure. Always use the built-in secrets module for passwords, tokens, and encryption keys.
Never check floats with a == b due to binary floating-point representation quirks. Use math.isclose(a, b, rel_tol=1e-9).
Use Python's secrets and string modules to generate an ultra-secure 12-character random password and a 6-digit banking OTP.
math.floor(-3.2)?random function selects a specified number of UNIQUE items from a sequence WITHOUT replacement?random.shuffle(my_list) return?random module to generate security tokens or passwords?In the next lesson, we will continue your intermediate Python journey with Datetime Module (10: Python Standard Libraries).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Project: Debugging a Student Grading App | Datetime Module |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.