Forum Archive

Importing a math module

Sharp Archer

Hello,
I am very new to coding and am trying to practice what I learned with making a quadratic formula, and learned I needed to I put in a math module. I downloaded sympy and dont know where to put the file or how to put the file in the right place. If someone knows how to do it, any help would be greatly appreciated.

Thank you,
Sharp Archer

ccc

The math module is built into Python. You do not need to download anything. Just import math
https://docs.python.org/3/library/math.html

deniswaka

Thanks for post!

Phlurim

I’ve had occasional puzzling error msgs while using Python’s built-in modules (import math for example). It seems that Python accepts either ‘math.pi’ or ‘pi’ in my main code. At other times, not.
What are the specific syntax rules for stipulating, in main code, the names of the functions inside imported Python modules.

Supplementary question: My code includes a function. My function calls a function inside a built-in Python module. Is it necessary to import the Python module from my main code, or from inside my function?

JonB

If you type from math import *, then you can use the symbols without typing math.

Or you can import specific names.

Eg

from math import pi
Or
from math import *

Both would expose pi

While

import math

Means you must use math.pi

Often, it is considered bad form to use import *, because then it can be hard to tell where some attribute or function comes from. By being explicit, your code will be easier to follow.

Usually, if you have imports that can be used in multiple functions , import at the top of the file.. if you have one import that is used in one function, and it is a big import, and the function is rarely used, then it can sometimes make sense to import inside a function.
.

ccc

The other thing to avoid is having a local Python file that shadows a Standard Library filename. For instance, a local math.py can throw a wrench into the works.