Python has a built-in math module that provides various mathematical functions and constants. It allows us to perform complex mathematical operations without having to write the code from scratch. To use the math module, you need to import it at the beginning of your code. Here's an example:
import math
Once you import the math module, you can use its functions and constants in your code. One of the most commonly used functions in the math module is `math.sqrt()`, which calculates the square root of a number. Here's an example:
import math result = math.sqrt(25) print(result) # Output: 5.0
5.0
In this code, we use the `math.sqrt()` function to calculate the square root of `25`. The result is stored in the variable `result` and then printed. The math module also provides other useful functions, such as `math.sin()`, `math.cos()`, and `math.exp()`, which calculate the sine, cosine, and exponential values, respectively. Here's an example:
import math angle = math.pi / 4 sin_value = math.sin(angle) cos_value = math.cos(angle) exp_value = math.exp(2) print(sin_value) # Output: 0.7071067811865476 print(cos_value) # Output: 0.7071067811865476 print(exp_value) # Output: 7.3890560989306495
0.7071067811865475 0.7071067811865476 7.38905609893065
In this code, we calculate the sine, cosine, and exponential values using the `math.sin()`, `math.cos()`, and `math.exp()` functions, respectively. The results are stored in variables and then printed. The math module also provides some useful constants, such as `math.pi` (the value of pi) and `math.e` (the value of Euler's number). Here's an example:
import math print(math.pi) # Output: 3.141592653589793 print(math.e) # Output: 2.718281828459045
3.141592653589793 2.718281828459045
In this code, we simply print the values of `math.pi` and `math.e`. These are just a few examples of what you can do with the math module in Python. There are many more functions and constants available for various mathematical operations that you can find in the [offical Python documentation](https://docs.python.org/3/library/math.html#module-math){target="_blank"}.