1

I have the following code which i want to execute :

import math

class A(object): 

    def someNum(self, num): 
        num = int(math.log2(num))
        return num

a = A()
a.someNum('9')

But it throws an exception :

Traceback (most recent call last):
  File "main.py", line 34, in <module>
    a.numToLoc('9')
  File "main.py", line 30, in numToLoc
    num = int(math.log2(num))
AttributeError: 'module' object has no attribute 'log2'

What am i missing ?

6
  • 3
    which version of Python are you using? Commented Jan 8, 2019 at 16:19
  • 8
    math.log2() was added in Python 3.3; you're apparently using an older version. Try math.log(num, 2) instead. Commented Jan 8, 2019 at 16:19
  • @MEdwin i am using 3x Commented Jan 8, 2019 at 16:19
  • which 3x. they're not all the same. theres 3.0 through to 3.7 Commented Jan 8, 2019 at 16:21
  • @Gammer Your also passing a string to somenum(). I think you want to pass an integer instead: a.someNum(9) Commented Jan 8, 2019 at 16:21

3 Answers 3

5

math.log2 was introduced in Python 3.3. You are probably using an earlier version.

In those earlier versions, you can use

math.log(num, 2)

instead.

Sign up to request clarification or add additional context in comments.

Comments

0

You have a file called math.py in the same directory as the code you're trying to run. Delete or rename it.

When you import math, Python walks through the directories in sys.path and imports the first file called math.py (or a directory called math with an __init__.py file inside) that it sees. The first entry in sys.path is the current directory, so it sees your math.py first.

See the documentation for modules or for the import statement.

Comments

-1

As already suggested either use Python3.3 or above or use math.log(num, 2)

Another slight modification is required.

Please change

a.someNum('9')

to

a.someNum(9)

Else this error occurs.

TypeError: a float is required

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.