How to Use Math Module in Python: Simple Guide with Examples
To use the
math module in Python, first import it with import math. Then you can call its functions like math.sqrt() for square root or math.pow() for power calculations.Syntax
Start by importing the math module. Then use the module name followed by a dot and the function name to call math functions.
- import math: Loads the math module.
- math.function_name(): Calls a function from the math module.
python
import math # Example syntax to use square root function result = math.sqrt(16) print(result)
Output
4.0
Example
This example shows how to use the math module to calculate the square root, power, and cosine of a number.
python
import math number = 9 sqrt_value = math.sqrt(number) # Square root power_value = math.pow(number, 2) # Number squared cos_value = math.cos(math.pi / 3) # Cosine of 60 degrees print(f"Square root of {number}: {sqrt_value}") print(f"{number} squared: {power_value}") print(f"Cosine of 60 degrees: {cos_value}")
Output
Square root of 9: 3.0
9 squared: 81.0
Cosine of 60 degrees: 0.5
Common Pitfalls
One common mistake is forgetting to import the math module before using its functions, which causes a NameError. Another is confusing math.pow() with the ** operator; math.pow() always returns a float.
python
try: print(sqrt(16)) # Wrong: math module not imported except NameError as e: print(f"Error: {e}") import math # Correct usage print(math.sqrt(16)) # Difference between math.pow and ** operator print(math.pow(2, 3)) # Returns float 8.0 print(2 ** 3) # Returns int 8
Output
Error: name 'sqrt' is not defined
4.0
8.0
8
Quick Reference
| Function | Description | Example |
|---|---|---|
| math.sqrt(x) | Returns the square root of x | math.sqrt(25) # 5.0 |
| math.pow(x, y) | Returns x raised to the power y as float | math.pow(2, 3) # 8.0 |
| math.sin(x) | Returns sine of x (radians) | math.sin(math.pi/2) # 1.0 |
| math.cos(x) | Returns cosine of x (radians) | math.cos(0) # 1.0 |
| math.factorial(n) | Returns factorial of n (integer) | math.factorial(5) # 120 |
Key Takeaways
Always import the math module with 'import math' before using its functions.
Use 'math.function_name()' to access math functions like sqrt, pow, sin, and cos.
math.pow() returns a float, while the '**' operator can return an int if both operands are ints.
Remember math functions expect radians for angles, not degrees.
Common errors include forgetting to import math or calling functions without the 'math.' prefix.