Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
math and random ModulesPython already provides basic arithmetic operators:
But sometimes we need more advanced operations such as:
Python provides useful standard library modules for these tasks.
The two important modules in this lesson are:
And for security-sensitive random values, we will also learn:
A module is a Python file that contains useful code such as functions, classes, and constants that we can use in our program.
For example:
After importing it, we can use:
You don't need to install math using pip.
It is included with Python.
math vs random| Module | Main Purpose | Example |
|---|---|---|
math | Mathematical calculations | math.sqrt(25) |
random | Pseudo-random values | random.randint(1, 10) |
secrets | Security-sensitive random values | Secure OTP/token generation |
math ModuleLet's start by importing it:
Now we can access many mathematical functions.
The math module provides some important mathematical constants.
Output:
For example:
Output:
math.sqrt()The sqrt() function calculates the square root.
Output:
Because:
Another example:
Output:
math.hypot()math.hypot() can calculate the length of the hypotenuse of a right triangle.
For example:
Output:
This is based on:
This function is useful for distance calculations.
ceil(), floor(), and trunc()Python provides several ways to handle decimal values.
math.ceil()ceil() rounds up toward positive infinity.
Output:
math.floor()floor() rounds down toward negative infinity.
Output:
Negative numbers are important:
Output:
math.trunc()trunc() removes the decimal part by moving toward zero.
Output:
ceil() vs floor() vs trunc()| Value | ceil() | floor() | trunc() |
|---|---|---|---|
4.2 | 5 | 4 | 4 |
4.9 | 5 | 4 | 4 |
-4.2 | -4 | -5 | -4 |
-4.9 | -4 | -5 | -4 |
math.factorial()A factorial multiplies a positive integer by all positive integers below it.
For example:
Python:
Output:
Another example:
Output:
GCD means Greatest Common Divisor.
For example:
Output:
The largest number that divides both 48 and 18 is 6.
LCM means Least Common Multiple.
Output:
So:
These functions are useful in mathematical and scheduling problems.
The math module provides:
These functions expect the angle in radians, not degrees.
This is important.
Humans commonly use degrees:
Python's trigonometric functions use radians.
For example:
Output:
Output:
For easier reading:
Output:
Use:
Example:
Output:
random ModuleNow let's learn about randomness.
Import the module:
The random module can be used for:
For example:
You will get a different value such as:
The value is:
random.randint()randint(a, b) generates a random integer between a and b.
Both endpoints are included.
Possible results:
This is useful for simulating a dice roll.
random.randrange()randrange() works similarly to Python's range().
For example:
Possible values include:
Notice that 30 is not included.
random.choice()choice() randomly selects one item from a sequence.
Possible output:
or:
or another fruit from the list.
random.sample()sample() selects multiple unique items without replacement.
Possible output:
The same student will not appear twice in that sample.
This can be useful for:
random.shuffle()shuffle() randomly rearranges the items in a list.
Possible output:
The original list is changed.
random.shuffle() returns None.
So don't write:
Instead:
Then use:
random.seed()The numbers generated by random are pseudo-random.
That means they look random, but the sequence is generated by an algorithm.
Sometimes we want the same sequence again.
This is useful for:
We can use random.seed().
If you run the same program again with the same seed, the sequence will repeat.
Output:
seed() is useful when you want repeatable random results.random vs secretsThis is a very important concept.
The random module is useful for:
But it should not be used for security-sensitive values such as:
For these tasks, Python provides:
The secrets module is designed for generating random values for security-sensitive applications.
secretsExample:
This generates a secure random number from:
For demonstration purposes, you can generate a secure six-digit code like this:
Possible output:
The result will normally be different each time.
In a real banking or authentication system, OTP delivery, expiration, rate limiting, verification, and storage must also be handled securely. Generating the number is only one part of a secure OTP system.
The secrets module can also choose characters securely.
Possible output:
random vs secrets| Requirement | Use |
|---|---|
| Dice game | random |
| Game simulation | random |
| Random test data | random |
| Shuffle cards | random |
| Scientific simulation | random |
| Security token | secrets |
| Password reset token | secrets |
| Authentication token | secrets |
| Security-sensitive random value | secrets |
sin()Don't:
if you mean 90 degrees.
Use:
shuffle() to return a listDon't:
Use:
shuffle() changes the list directly and returns None.
random for securityDon't use:
for security-sensitive authentication codes.
Use a security-focused approach such as:
| Situation | Don't | Do |
|---|---|---|
| Square root | Write your own unnecessarily | math.sqrt() |
| Trigonometry | Pass degrees directly | Convert with math.radians() |
| Random game number | secrets unnecessarily | random.randint() |
| Security token | random | secrets |
| Shuffle list | result = random.shuffle(list) | random.shuffle(list) |
| Repeatable testing | Expect random sequence to repeat automatically | Use random.seed() |
sqrt()?math.floor(-4.2)?random.randint(1, 10) generate?random.shuffle() do?math.radians() before math.sin() when working with degrees?Now let's combine math and random in a fun simulation.
We will create a simple 6-ball cricket simulation.
The program will:
random.choices()math.hypot() for a simple distance calculationAfter running the program, try these changes.
Currently:
Try:
Observe what happens.
Add another possible outcome:
Then update the weights.
Add:
near the beginning of the program.
Run the program multiple times.
Observe whether the same sequence is produced.
Try:
Then observe the new result from:
In this lesson, you learned:
math modulemath.pi, math.e, and math.taumath.sqrt()math.hypot()math.ceil()math.floor()math.trunc()math.factorial()math.gcd()math.lcm()random.random()random.randint()random.randrange()random.choice()random.sample()random.shuffle()random.seed()random should not be used for security-sensitive randomnesssecrets is used for security-sensitive random valuesIn the next lesson, we will continue your Python learning journey with String Introduction (5: Strings).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Mathematical Operations | String Introduction |
Test your understanding of this lesson with 6 questions. Each question has one correct answer.