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

Sheikh Ahmad Shah picture Sheikh Ahmad Shah · Jun 4, 2015 · Viewed 61.2k times · Source

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?

Answer

fenceop picture fenceop · Jun 4, 2015

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.