Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"from math import sqrt" works but "import math" does not work. What is the reason?

I am pretty new in programming, just learning python.

I'm using Komodo Edit 9.0 to write 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 "sqrt" function of that module doesn't work. What is the reason behind this? Can I fix it somehow?

like image 302
Sheikh Ahmad Shah Avatar asked Jun 04 '15 14:06

Sheikh Ahmad Shah


People also ask

Do you need to import math for sqrt?

The sqrt() function is the part of math module so you need to import it before using in Python program. The value of x must be greater than 0.

How do you use import sqrt in math?

To use sqrt() , you will have to import the math module, as that's where the code to carry out the function is stored. By prefixing “math” to sqrt() , the compiler knows you are using a function, sqrt() , belonging to the “math” library. The result of the square root function is a floating point number (float).

How does the sqrt function imported from math differs from that imported from Cmath?

sqrt are going to be nearly identical. just because of the lookup of sqrt in the math module. cmath is different and will be slower. It is for math on complex numbers, which is why it's returning complex numbers.

What is the difference between import math and from math import *?

The only difference is convenience and nothing else. Import aliases/unrolling is just namespace thing. There's no difference in performance or footprint.


3 Answers

You have two options:

import math
math.sqrt()

will import the math module into its own namespace. This means that function names have to be prefixed with math. This is good practice because it avoids conflicts and won't overwrite a function that was already imported into the current namespace.

Alternatively:

from math import *
sqrt()

will import everything from the math module into the current namespace. That can be problematic.

like image 68
fenceop Avatar answered Oct 01 '22 08:10

fenceop


If you only import math to call sqrt function 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 from math import sqrt brings you the sqrt function, but import math only brings you the module.

like image 20
metersk Avatar answered Oct 01 '22 09:10

metersk


When you only use import math the sqrt function comes in under a different name: math.sqrt.

like image 21
randomusername Avatar answered Oct 01 '22 08:10

randomusername