.py appended.
# myMath.py
PI = 3.14159
def add(a, b):
return a + b
def test_pi():
print(PI)
>>> import myMath
>>> print(myMath.PI, myMath.add(3, 5))
>>> from myMath import PI
>>> print(PI)
>>> from myMath import add as addition
>>>print(addition(3, 7))
# myMath2.py
def gcd(a, b):
if a == 0:
return b
else:
return gcd(b % a, a)
print(f'[TEST] gcd(48, 36) = {gcd(48, 36)}')
if __name__ == "__main__":
print(f'[TEST] gcd(48, 36) = {gcd(48, 36)}')
if-else) block.
module.attribute)
after the module is imported.
import myMath
myMath.test_pi()
print(myMath.PI)
# myMath3.py
'This is my math module.'
PI = 3.14159
def add(a, b):
'''Adding two numbers
add(a, b)
Return the summation of a and b.'''
return a + b
def test_pi():
"Testing function to show the value of PI"
print(PI)
dir(myMath3) shows the attributes of the module
"myMath3".
help(myMath3) can generate
documentation of the module myMath3 automatically.
help(myMath3.add).
x = 20
def f():
x = 40 # a local 'x' is created
print(x)
f()
print(x) # still 20
global statement allows your function to modify a global variable:
x = 20
def f():
global x
x = 40
print(x)
f()
print(x) # Now it's 40
sys.modules (the module cache).
On subsequent imports, Python checks if the module is already in
sys.modules and simply returns the cached version without re-executing the file.
sys.modules: