Python 3 – Modules
Python is a powerful language that has been widely used for various programming purposes. One of the features that make Python a much-loved language is its modules. In this article, we will talk about Python 3 – Modules and learn how to use them to enhance your code.
What are Modules?
Modules are files that contain Python code that other Python programs can use. These files contain functions, classes, and variables that programmers can use to make their code more efficient and easy to read.
Python has its own built-in modules that you can use but you can also create your own modules. Creating a module is just creating a file with .py extension under the directory where the Python script is located.
The benefit of using modules is that you can easily share code between different parts of your program or different programs altogether without having to cut and paste code. They allow you to reuse code without repeating yourself.
Built-in Modules
Python has a large number of built-in modules that are ready to use. Some of these modules are:
random
The random module is a Python module that generates a random number or a list of numbers. It has different functions that generate random numbers in various ranges.
import random
# generate a random number between 0 and 100
randomNumber = random.randint(0, 100)
print(randomNumber)
# generate a random number between 0 and 1
randomNumber2 = random.random()
print(randomNumber2)
datetime
The datetime module helps in working with dates and times. It has classes that allow you to create and manipulate date or time objects.
import datetime
# get the current date and time
now = datetime.datetime.now()
print(now)
# get the date only
date = datetime.date.today()
print(date)
Creating and Using Modules
Creating a module is as simple as creating a file and putting some Python code in it. To use the code in the module, you need to import the module.
Here is an example of a simple module that defines a function:
# hello.py
def sayHello(name):
print("Hello, " + name + "!")
To use the module, you would import it like this:
import hello
hello.sayHello("John")
from…import
Instead of importing the entire module, you can choose to import only specific functions, variables, or classes.
from hello import sayHello
sayHello("John")
as
You can also use the as
keyword to give a module, function, or class a different name.
import hello as h
h.sayHello("John")
Conclusion
In conclusion, modules are an essential part of Python programming. They help you organize your code, reduce redundancy, and make code more efficient. In this article, we have learned how to create and use modules, and we have also seen some built-in modules that Python has to offer. With these skills, you can start building more powerful and efficient Python programs.