Modules and Packages
Python Modules
A module is a file containing definition of functions, classes, variables,
constants or any other Python object. Contents of this file can be made
available to any other program. Python has the import keyword for this
purpose.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import
statement.
• Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Re-naming a Module
You can create an alias when you import a module, by using the as
keyword.
Example:
import mymodule as mx
mx.greeting("Jonathan")
Built-in Modules
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Import From Module
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Python Math
Python has a set of built-in math functions, including an extensive math
module, that allows you to perform mathematical tasks on numbers.
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
Python Math
import math
x = math.sqrt(64)
print(x)
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
Python RegEx
• A RegEx, or Regular Expression, is a sequence of characters that forms
a search pattern.
• RegEx can be used to check if a string contains the specified search
pattern.
Example:
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
RegEx Functions
Function Description
findall Returns a list containing all matches
Returns a Match object if there is a match anywhere
search
in the string
Returns a list where the string has been split at each
split
match
sub Replaces one or many matches with a string