"from math import sqrt" works, but "imported math" doesn't work. What is the reason?

I'm new to programming just learning python.

I am using Komodo Edit 9.0 for writing codes. So when I write "from math import sqrt" I can use the "sqrt" function without any problem. But if I only write "import math" then the "sqrt" function of this module does not work. What is the reason for this? Can I fix this?

+3


source to share


4 answers


You have two options:

import math
math.sqrt()

      

imports the module math

into its own namespace. This means that function names must be prefixed math

. This is a good practice because it avoids conflicts and will not overwrite a function that has already been imported into the current namespace.



As an alternative:

from math import *
sqrt()

      

will import everything from the module math

into the current namespace. This can be problematic .

+7


source


If you import math

only call import math

, you need to do this:

In [1]: import math

In [2]: x = 2

In [3]: math.sqrt(x)
Out[3]: 1.4142135623730951

      



This is because it from math import sqrt

provides you with a function sqrt

, but import math

only brings you a module.

+3


source


When you use only import math

the function sqrt

part under a different name: math.sqrt

.

+2


source


If you want the square root, you can also just multiply the number by 0.5.

144 ** 0.5

      

gives the result:

12.0

      

0


source







All Articles