Python Modules
A module is a Python file that can contain the variables, functions and the classes.
Why Use Modules?
Modules allow us to split our code into multiple files. Instead of writing all our codes inside a single Python file, we can use modules.
Creating a Module
There is nothing so special with creating a module, simply write your Python the code and save it with the .py file an extension.
In this example, we have a module saved as my_module.py and it contains the following code:
# this is my_module.py
first_name = "John"
last_name = "Doe"
def add(x, y):
return x + y
def multiply(x, y):
return x y
After that, to use my_module.py, we need to import it.
To import, use the import statement and the module name.
import my_module
Now we can use the module's variables and functions by following this syntax:
module_name.variable_name module_name.function_name()
In this example, the code below is saved as main_code.py and it imports the my_module.py.
# this is main_code.py import my_module
print(my_module.first_name + my_ print(my_module.add(3, 4))
How to demonstrate this on a PC?
If you have a PC that has Python installed and if you want to demonstrate importing modules, follow these steps:
1) Create a folder named example.
2) Copy the code in the first example and save it as my_module.py.
3) Copy the code in the previous example and save it as main_code.py.
4) Open the command-line (cmd) in the example folder.
5) Type python main_code.py.
6) Press Enter.
The program should then output the following:
John Doe
7
Using Aliases
We can use an alias to refer to the module.
To use an alias, use the as keyword.
import my_module as my # now we can use the module usin
print(my.first_name + my.last_na print(my.add(3, 4))
Importing Parts of a Module
- We can choose to import only some parts of a module.
- Use the from keyword to import a part of the module.
- In this example, we will import the first_name variable and access it directly.
from my_module import first_name
# now we can directly use # the first_name variable print(first_name
The dir() Function
The dir() function returns a list of all the variables, functions and classes available in a module.
import my_module x = dir(my_module)
print(x)
Built-in Modules
Python has many useful built-in modules that we can use to make coding easier.
Built-in modules can be imported without having to create them.
In this example, we will import the sysconfig module and use its get_python_version() to return the Python version we're using.
import sysconfig
x = sysconfig.get_python_versior print(x)
1- Python Date and Time
The datetime module allows us to work with dates.
To use the datetime module, import it first:
import datetime
Current Date and Time
The datetime.datetime.now() method returns the current date and time.
import datetime
now = datetime.datetime.now() print(now)
The Date Object
The date object represents a date (year, month and day).
To create a date object, import it from the datetime module first:
from datetime import date
To get the current date, use the date.today() method.
from datetime import date
today = date.today()
print("Current date: ", today)
The Datetime Object
The datetime object contains the following information: year, month day, hour, minute, second, microsecond
Before we can create a datetime object, import the datetime module first:
import datetime
To get the current datetime object, use the datetime.datetime.today() method.
import datetime
datetime_obj = datetime.datetime print("Current datetime: ", date
Create a Custom Datetime Object
We can create a custom datetime object by using the datetime.datetime() class constructor.
The datetime.datetime() constructor takes the following arguments: year, month, day,
hour, minute, second, microsecond.
Here is an example:
import datetime
datetime_obj = datetime.datetime print("Datetime: ", datetime_obj
Format Datetime String
- In the previous examples, we have only printed the datetime object.
- It would be better if we can format the date and print it as a string so that it becomes more readable.
- The strftime() method allows us to do that.It takes one parameter, the format.
import datetime
d = datetime.datetime.today()
print(d.strftime("%B %d %Y"))
2 - What is JSON?
- JSON stands for JavaScript Object Notation.
- JSON contains data that are sent or received to and from a server.
- JSON is simply a string, it follows a format similar to a Python dictionary.
Example
Here is an example of a basic JSON string:
x = '{"first_name": "John", "rahul"}
print(x)
JSON to Dictionary
Before we can individually access the data of a JSON, we need to convert it to a Python dictionary first.
To do that, we need to import the json module.
import json
- To convert from JSON to dictionary, use the json.loads() method.
- This method parses a JSON and returns a dictionary.
x = '{"first_name": "John", "rahul"}
my_json = json.loads(x)
Now we can access its values just like how we do it on a dictionary.
a = my_json["first_name"]
b = my_json["last_name"]
c = my_json["age"]
Dictionary to JSON
To convert a dictionary to a JSON, use the json.dumps() method.
import json
x = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30}
,
my_ison = json.dumps(x)
print(my_json)
When you convert a dictionary to a JSON, the values are converted to their Learn JavaScript equivalent data type:
Formatting a JSON
A JSON file can be formatted or be "prettified" using the indent parameter of the json.dumps() method.
In this example, the json file is indented using 4 whitespaces.
import json
x = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30
,my_json = json.dumps(x, indent =
print(my_json)
Saving JSON Files
Since JSON is simply just a string, then it can be saved just like a plain text.
When saving JSON files, make sure you save them with the .json file extension e.g. filename.json.
,
"first_name": "John",
"last_name": "Doe",
"age": 30
,
You can try it by copying the code above, pasting it on Notepad then saving it as example.json.
3 - Python Random
The random module lets us generate a random number.
To use the random module, import it first:
import random
Now, we can start generating a random number.
The random.random() method generates a random floating point in the range of 0.0 to 1.0.
import random
y = random.random()
print(y)
The random.randint(x, y) method generates a random integer in the range of x to y.
import random
y = random.randint(1, 9)
print(y)
4 - Python Math
The math module gives us access to mathematical functions.To use the math module, import it first:
import math
Now we can start using it.One of the most useful functions of the math module is the sqrt() function.
The math.sqrt() function returns the square root of the given number.
import math
x = math.sqrt(4)
print(x)
The math.pow(x, y) function returns x raised to the power of y.
import math
x = math.pow(5, 6) # same as 5, print(x)
The math.ceil() method rounds up a number to its nearest integer. The math.floor() method rounds down a number to its nearest integer.
import math
x = math.ceil(5.6)
y = math.floor(3.6)
print(x)
print(y)
Math Constants
The math module also contains math constants like the pi and the mathematical constant e.
import math
x = math.pi
y = math.e
print(x)
print(y)
Trigonometric Functions
The math module also contains trigonometric functions.The math.cos(x) function returns the cosine of x radians.
import math
x = math.cos(8)
print(x)
The math.sin(x) function returns the sine of x radians.
import math
x = math.sin(8)
print(x)
The math.tan(x) function returns the tangent of x radians.
import math
x = math.tan(8)
print(x)
Built-in Mathematical Functions
Python also has built-in math functions, which you can use without importing the math module. The abs() function returns the absolute value of the a number.
The absolute value of a number is its magnitude or size, negatives are not allowed.
x = abs(4)
= abs(-4)
print(x)
print(y)
The min() function returns the lowest number from the given arguments.
x = min(40, 50, 60)
print(x)
The max() function returns the largest number from the given arguments.
x = max(40, 50, 60)
print(x)