AttributeError: module ‘math’ has no attribute ‘sine’

Loading

The error message:

AttributeError: module 'math' has no attribute 'sine'

occurs when you try to access an attribute (function, variable, or object) that does not exist in the math module.


1. Causes and Solutions

Cause 1: Typo in Function Name

The Python math module provides a sin() function, not sine().

Incorrect Code:

import math
print(math.sine(30)) # 'sine' does not exist

Error Output:

AttributeError: module 'math' has no attribute 'sine'

Solution: Use the Correct Function Name

import math
print(math.sin(math.radians(30))) # Use math.sin() and convert degrees to radians

Output: 0.5


Cause 2: Importing the Wrong Module

If you have a local file named math.py, Python might be importing it instead of the built-in math module.

Incorrect Scenario:

  • You have a file math.py in your project.
  • Python imports your file instead of the built-in module.

Solution:

  1. Check for a Local File Named math.py
    • If it exists, rename it (e.g., my_math.py).
  2. Check the Import Path import math print(math.__file__) # Check which file is being imported If it shows a local file instead of Python’s standard library, delete or rename it.

Cause 3: Importing a Module Incorrectly

If you accidentally assign a variable named math, it will overwrite the module.

Incorrect Code:

import math
math = 10 # Overwrites the module!
print(math.sin(30)) # Error!

Solution: Avoid Overwriting Module Names

import math
print(math.sin(math.radians(30))) # No error

2. Best Practices to Avoid AttributeError

Use dir(math) to check available functions

import math
print(dir(math)) # Lists all valid attributes

Avoid naming variables or files as built-in module names
Check for typos in function names

Leave a Reply

Your email address will not be published. Required fields are marked *