{"id":24990,"date":"2023-03-27T08:36:00","date_gmt":"2023-03-27T03:06:00","guid":{"rendered":"https:\/\/tocxten.com\/?page_id=24990"},"modified":"2023-03-28T21:36:54","modified_gmt":"2023-03-28T16:06:54","slug":"python-modules","status":"publish","type":"page","link":"https:\/\/tocxten.com\/index.php\/python-modules\/","title":{"rendered":"Python Modules"},"content":{"rendered":"\n<p class=\"has-medium-font-size\"><strong>As the programs become more lengthy and complex, there arises a need for the tasks to be split into smaller segments called modules.<\/strong> In Python, a module is a file containing Python variables, definitions, statements and functions. A module can be considered as a library or a package that contains reusable code which can be imported and used in other Python programs.\u00a0<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Modules also make it easier to reuse the same code in more than one program. If we have written a set of functions that is needed in several different programs , we can place those functions in a module. Then we can import the module in each program that needs to call one of the functions . Once we import a module we can refer to any of its functions or variable in our program.<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">There are several types of modules in Python:<\/p>\n\n\n\n<ol class=\"has-medium-font-size wp-block-list\"><li><strong>Built-in modules<\/strong>: These are the modules that are included in the Python standard library and can be used without any additional installation. Examples of built-in modules are &#8220;os&#8221;, &#8220;sys&#8221;, &#8220;math&#8221;, &#8220;random&#8221;, etc.<\/li><li><strong>Third-party modules<\/strong>: These are the modules that are developed by third-party developers and are not included in the Python standard library. These modules can be installed using package managers like pip. Examples of third-party modules are &#8220;NumPy&#8221;, &#8220;Pandas&#8221;, &#8220;Matplotlib&#8221;, etc.<\/li><li><strong>User defined<\/strong> <strong>Custom modules:<\/strong> These are the modules that are created by the user for specific purposes. Custom modules can be created by writing Python code and saving it in a file with a &#8220;.py&#8221; extension.<\/li><li><strong>Package modules:<\/strong> These are the modules that are organized into a directory hierarchy called a package. A package can contain multiple modules, sub-packages, and even other packages. Package modules are used to organize large projects and avoid naming conflicts between modules.<\/li><\/ol>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#deeaef\">1. <strong>User defined Modules<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">In Python, a module is a file containing Python definitions and statements. The file name is the module name with the suffix <code>.py<\/code>. Modules allow you to organize your code into separate files, making it easier to maintain and reuse code across different projects.<\/p>\n\n\n\n<p class=\"has-medium-font-size\">Here&#8217;s an example of a simple module:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># example.py\n\ndef add_numbers(a, b):\n    return a + b\n\ndef multiply_numbers(a, b):\n    return a * b<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">In this example, we have defined two functions, <code>add_numbers<\/code> and <code>multiply_numbers<\/code>, which can be used by other Python code. To use these functions, we can import the module nto our code like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import example\n\nresult = example.add_numbers(2, 3)\nprint(result)  # Output: 5\n\nresult = example.multiply_numbers(2, 3)\nprint(result)  # Output: 6<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">In addition to importing the entire module, we can also import specific functions from a module like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from example import add_numbers\n\nresult = add_numbers(2, 3)\nprint(result)  # Output: 5<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">We can also give a module an alias using the <code><strong>as<\/strong><\/code> keyword:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import example as ex\nresult = ex.add_numbers(2, 3)\nprint(result)  # Output: 5<\/code><\/pre>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#dfe6d8\"><strong>Example : <\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">Design a new Python module called <strong>userdefined<\/strong> by defining all functions as illustrated below. Save the file as userdefined.py and run the file.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-84.png\" alt=\"\" class=\"wp-image-25208\" width=\"337\" height=\"288\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-84.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-84-300x256.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-84-760x649.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-84-600x513.png 600w\" sizes=\"auto, (max-width: 337px) 100vw, 337px\" \/><\/figure>\n\n\n\n<p class=\"has-medium-font-size\">Start a new script with name importexample.py (\/ipynb). Next call each function with and without arguments as per the requirements. Run the program and get the output as illustrated below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-85.png\" alt=\"\" class=\"wp-image-25211\" width=\"395\" height=\"319\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-85.png 667w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-85-300x242.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-85-600x484.png 600w\" sizes=\"auto, (max-width: 395px) 100vw, 395px\" \/><\/figure>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#d8e1e5\">2. <strong>Inbuilt Python Modules <\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\">Python comes with a set of built-in modules that provide a wide range of functionalities, such as working with files, mathematical operations, date and time handling, and more. Here are some examples of built-in modules in Python:<\/p>\n\n\n\n<ol class=\"has-medium-font-size wp-block-list\"><li><strong><code>math<\/code> module:<\/strong> The <code>math<\/code> module provides various mathematical operations such as trigonometric functions, logarithmic functions, constants like <code>pi<\/code>, and more.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>import math\n\n# Calculate the square root of 25\nsqrt_val = math.sqrt(25)\nprint(sqrt_val)  # Output: 5.0\n\n# Calculate the value of pi\npi_val = math.pi\nprint(pi_val)  # Output: 3.141592653589793<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">2. <strong><code>os<\/code> module: <\/strong>The <code>os<\/code> module provides a way to interact with the operating system, such as working with files and directories, environment variables, and more.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\n# Get the current working directory\ncwd = os.getcwd()\nprint(cwd)  # Output: \/home\/user\/Documents\n\n# List all the files and directories in a directory\ndir_list = os.listdir('.')\nprint(dir_list)  # Output: &#91;'file1.txt', 'file2.txt', 'folder']<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">3. <strong><code>datetime<\/code> module:<\/strong> The <code>datetime<\/code> module provides classes to work with date and time values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import datetime\n\n# Get the current date and time\ncurrent_time = datetime.datetime.now()\nprint(current_time)  # Output: 2023-03-27 12:30:00.000000\n\n# Create a date object\ndate_obj = datetime.date(2022, 7, 4)\nprint(date_obj)  # Output: 2022-07-04<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">4.<strong> <code>random<\/code> module:<\/strong> The <code>random<\/code> module provides functions to generate random numbers, random selections from a sequence, and more.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Generate a random number between 0 and 1\nrand_val = random.random()\nprint(rand_val)  # Output: 0.325\n\n# Shuffle a list\nmy_list = &#91;1, 2, 3, 4, 5]\nrandom.shuffle(my_list)\nprint(my_list)  # Output: &#91;2, 5, 1, 4, 3]<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dfe5e8;font-size:30px\"><strong>Importing Modules in a python Program<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Python language provides two important methods to import modules in a program which are as follows :<\/strong><\/p>\n\n\n\n<ul class=\"has-medium-font-size wp-block-list\"><li><strong>Import statement :<\/strong> To import entire module<\/li><li><strong>From<\/strong> :To import all functions or selected ones<\/li><li><strong>Import <\/strong>: To use module in a program , we import them using the import statement.<\/li><\/ul>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Syntax :<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-medium-font-size\"><code> import modulename1 &#91; modulname2,\u2014\u2014]<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>It is the simplest and the most common way to use modules in our code.<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Example\u00a0<\/strong>:  Importing math module<\/p>\n\n\n\n<p class=\"has-medium-font-size\">The <code>math<\/code> module in Python provides a wide range of mathematical functions. Here is a list of some of the most commonly used functions along with examples of how to use them:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import math\r\nprint(math.ceil(3.5)) # Output: 4\nprint(math.floor(3.5)) # Output: 3\nprint(math.sqrt(16)) # Output: 4.0\nprint(math.pow(2, 3)) # Output: 8.0\nprint(math.exp(2)) # Output: 7.38905609893065\nprint(math.log(10)) # Output: 2.302585092994046\nprint(math.log10(100)) # Output: 2.0\nprint(math.radians(180)) # Output: 3.141592653589793\nprint(math.degrees(3.141592653589793)) # Output: 180.0\nprint(math.sin(math.pi\/2)) # Output: 1.0\nprint(math.cos(math.pi\/2)) # Output: 6.123233995736766e-17\nprint(math.tan(math.pi\/4)) # Output: 0.9999999999999999<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e3e8ea;font-size:30px\"><strong>Random module (Generating random numbers)<\/strong><\/p>\n\n\n\n<p>The <code>random<\/code> module in Python provides functions to generate random numbers. Here are some commonly used functions for generating random numbers:<\/p>\n\n\n\n<ol class=\"has-medium-font-size wp-block-list\"><li><code>random()<\/code> &#8211; Returns a random float number between 0 and 1.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nprint(random.random()) # Output: 0.48859901707920826<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">2. <code>randint(a, b)<\/code> &#8211; Returns a random integer between <code>a<\/code> and <code>b<\/code> (inclusive).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nprint(random.randint(1, 10)) # Output: 5<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">3. <code>uniform(a, b)<\/code> &#8211; Returns a random float number between <code>a<\/code> and <code>b<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nprint(random.uniform(1.0, 2.0)) # Output: 1.5788203993480903<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">4. <code>choice(seq)<\/code> &#8211; Returns a random element from the sequence <code>seq<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nprint(random.choice(&#91;1, 2, 3, 4, 5])) # Output: <\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">5. <code>shuffle(seq)<\/code> &#8211; Shuffles the sequence <code>seq<\/code> in place.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nmy_list = &#91;1, 2, 3, 4, 5]\r\nrandom.shuffle(my_list)\r\nprint(my_list) # Output: &#91;2, 5, 1, 4, 3]<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">6. <code>sample(population, k)<\/code> &#8211; Returns a list of <code>k<\/code> unique elements chosen randomly from the <code>population<\/code> sequence. The <code>population<\/code> can be a list, set, or tuple.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nmy_list = &#91;1, 2, 3, 4, 5]\r\nprint(random.sample(my_list, 3)) # Output: &#91;2, 3, 4]<\/code><\/pre>\n\n\n\n<ol start=\"7\" class=\"has-medium-font-size wp-block-list\"><li><code>randrange([start,] stop[, step])<\/code> &#8211; Returns a randomly selected element from the range created by <code>start<\/code>, <code>stop<\/code>, and <code>step<\/code>.(Default start = 0 and stop = limit -1)<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\r\nprint(random.randrange(0, 10, 2)) # Output: 4\nprint(random.randrange(30)) # Output: 15<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">These are just a few examples of the many functions available in the <code>random<\/code> module. Note that the functions in the <code>random<\/code> module are pseudo-random number generators, meaning that the numbers are not truly random but are generated using a deterministic algorithm. The random module can be useful for generating test data, simulations, and games.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dbe8ed;font-size:30px\"><strong>Importing the sys and keyword modules :<\/strong><\/p>\n\n\n\n<p>Python includes\u00a0<strong>\u201csys\u201d and \u201ckeyword\u201d<\/strong>\u00a0modules that are useful for interrogating the Python system itself. The keyword module contains a list of all Python keywords in its\u00a0<strong>kwlist<\/strong>\u00a0attribute and provides as\u00a0<strong>iskeyword ()<\/strong>\u00a0method if you want<br>to rest a word.<\/p>\n\n\n\n<p>The <code>sys<\/code> module provides access to some variables and functions that interact with the Python interpreter. Here is an example of how to use the <code>sys<\/code> module to access the command line arguments passed to a Python script:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import sys\r\n\r\nif len(sys.argv) > 1:\r\n    print(\"Hello, \" + sys.argv&#91;1] + \"!\")\r\nelse:\r\n    print(\"Hello, world!\")<\/code><\/pre>\n\n\n\n<p>In this example, we use the <code>argv<\/code> variable from the <code>sys<\/code> module to access the list of command line arguments passed to the script. If there is at least one argument, we print a customized message. Otherwise, we print the default message &#8220;Hello, world!&#8221;.<\/p>\n\n\n\n<p>The <code>keyword<\/code> module provides a list of keywords in Python. These keywords are reserved for use by the language itself and cannot be used as variable names, function names, or any other identifiers. Here is an example of how to use the <code>keyword<\/code> module to list all the keywords in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import keyword\r\n\rprint(keyword.kwlist)<\/code><\/pre>\n\n\n\n<p>The output of this script will be a list of all the keywords in Python, which includes words such as <code>if<\/code>, <code>else<\/code>, <code>while<\/code>, <code>for<\/code>, <code>def<\/code>, <code>class<\/code>, and so on.<\/p>\n\n\n\n<p>Both the <code>sys<\/code> module and the <code>keyword<\/code> module are part of the standard library in Python and are available for use without the need for any additional installation or setup.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86-1024x132.png\" alt=\"\" class=\"wp-image-25240\" width=\"599\" height=\"77\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86-1024x132.png 1024w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86-300x39.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86-768x99.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86-760x98.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86-600x77.png 600w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-86.png 1032w\" sizes=\"auto, (max-width: 599px) 100vw, 599px\" \/><\/figure>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#e9eef0\"><strong>Python Module sys.path<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"768\" height=\"467\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-87.png\" alt=\"\" class=\"wp-image-25241\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-87.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-87-300x182.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-87-760x462.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-87-600x365.png 600w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#d9dfe1\"><strong>To display the list of All Python Keywords<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"190\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-88.png\" alt=\"\" class=\"wp-image-25244\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-88.png 1024w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-88-300x56.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-88-768x143.png 768w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-88-760x141.png 760w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/03\/image-88-600x111.png 600w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p class=\"has-background has-medium-font-size\" style=\"background-color:#eaf0f2\"><strong>Questions for Practice<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\"><li>What are modules in Python and why are they useful?<\/li><li>How do you create your own modules in Python?<\/li><li>How do you import a module in Python and what are the different ways to do it?<\/li><li>What is the difference between the <code>import<\/code> and <code>from<\/code> statements in Python?<\/li><li>What is the purpose of the <code>__init__.py<\/code> file in a Python package?<\/li><li>What is the difference between a package and a module in Python?<\/li><li>What is the <code>sys.path<\/code> variable and how does it relate to Python modules?<\/li><li>What is a namespace in Python and how does it relate to modules?<\/li><li>What is a built-in module in Python and how do you use it?<\/li><li>What is the <code>os<\/code> module in Python and how can it be used for file and directory operations?<\/li><li>What is the <code>datetime<\/code> module in Python and how do you use it to work with dates and times?<\/li><li>What is the <code>math<\/code> module in Python and what are some of the commonly used functions in it?<\/li><li>What is the <code>random<\/code> module in Python and how can it be used to generate random numbers?<\/li><li>What is the <code>csv<\/code> module in Python and how can it be used to read and write CSV files?<\/li><li>What is the <code>json<\/code> module in Python and how can it be used to read and write JSON files?<\/li><li>What is the <code>re<\/code> module in Python and how can it be used for regular expressions?<\/li><li>What is the <code>pickle<\/code> module in Python and how can it be used for object serialization and deserialization?<\/li><li>What is the <code>urllib<\/code> module in Python and how can it be used for HTTP requests and responses?<\/li><li>What is the <code>unittest<\/code> module in Python and how can it be used for unit testing?<\/li><li>What is the <code>logging<\/code> module in Python and how can it be used for logging messages in a Python application?<\/li><li>What does the\u00a0<strong><em>import allname<\/em><\/strong>\u00a0statement do?<\/li><li>If you had a function named\u00a0\u00a0<strong>radio()<\/strong>\u00a0in a module named\u00a0<strong>car<\/strong>\u00a0who would you call it after importing\u00a0<strong><em>car<\/em><\/strong>.<\/li><\/ol>\n","protected":false},"excerpt":{"rendered":"<p>As the programs become more lengthy and complex, there arises a need for the tasks to be split into smaller segments called modules. In Python, a module is a file&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":"","_links_to":"","_links_to_target":""},"class_list":["post-24990","page","type-page","status-publish","hentry"],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/24990","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/comments?post=24990"}],"version-history":[{"count":23,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/24990\/revisions"}],"predecessor-version":[{"id":25249,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/24990\/revisions\/25249"}],"wp:attachment":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/media?parent=24990"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}