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?
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.
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).
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.
The only difference is convenience and nothing else. Import aliases/unrolling is just namespace thing. There's no difference in performance or footprint.
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.
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.
When you only use import math
the sqrt
function comes in under a different name: math.sqrt
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With