Last Updated On By Khizer Ali
Python is a progressive programming language and is known for its optimization. Python skims down unnecessary aspects of programming and makes the tools rich in utilization. In this article, we will cover the difference between function vs module in Python.
A function is a block of organized, reusable code that is used to perform a single, related action. There are two types of functions, user-defined and built-in functions. Built-in functions are provided by python to help in coding like print(), input(), etc.
The difference between function vs module in Python is that a function is more specific to a task, to fulfill a functionality while a module defines classes, functions, attributes, etc.
Let’s take a look at how a function is defined and called.
Here is a simple function that prints a string and terminates. We can alter this code to make it a bit more useful.
Output
Passing an argument to the function we can make this code more reusable by not hard coding the string.
Here, we don’t have to rewrite the function or define it repeatedly for different strings. This function can be called many times in the entire application
Now, let’s go through how a module is defined and used.
You can simply create a python file that has a .py extension and save it in your local repository. Now you can use this file to import it in your application to include the module’s functionality in your software.
You can simply use the import command to include multiple modules.
import module1, module2….
Note that as soon as we have added the module the code is executed without having to call any function. That is because we have defined and called the functions in the file. Therefore, the whole file is executed first treated as a bigger scale function, being executed while being called.
We can remove the function calls from the module we created and can access the functions, attributes, classes, and all the other valuables through the dot(.) operator.
module1.func1()
module2.name
Output:
Modules and functions may seem similar to their purpose which is reusability. However, modules are on a larger scale as they can use multiple classes, functions, and attributes to fulfil larger functionalities. While functions are more specific to a particular task on a smaller scale.
Thus, a function is a smaller, specific type of a module that can be called simultaneously, repeated multiple times without having to define it each time.