Working with Python – Module

Introduction

In this blog post, we are going to discuss about Python Module. Before that, we have to understand what the module is. Module is a code Library. Remember, when we are at C or C++, we are using #Include statement at

beginning of the code to call specific code library.

How to Create a Module

If we need to create a module, we just save our code with .py extension.

def greeting(name):
  
print("Hello, " + name)

 

Suppose, we have the above code and we are just saving the code in the name of mymodule.py

Calling Module

 

import mymodule
mymodule.greeting(
"Mayuree")

 

Hello, Mayuree

 

If we are looking at the calling procedure.

mymodule.greeting("Mayuree")

mymodule – Module Name

greeting – Function Name

 

Can we assign Variable in Module

 

Module can have function that we already demonstrate. However, it can also have Variables.

Example:

File Name: mymodule.py

Developers = {
  
"name""Mayuree",
  
"age"21,
  
"country""UK"
}


Note: We are using Dictionary in the module.

Now we have to import it.

import mymodule

a = mymodule.Developers [
"name "]
print
(a)

Mayuree

 

Creating Alias in Module Import


Example:


import mymodule as mm

a = mm.Developers [
"name "]
print
(a)

Mayuree

 

Built-in Module

The python supports several Built-in Module. For that, you have to check the documentation.


Example:


import platform
x = platform.system()
print
(x)


Provides us the system Information.

 

Hope you like that.


Comments

  1. Hi this blog is helpful as usual. I have one doubt on 'a = mm.Developers ["name "]' syntax. When I ran it threw error for extra space after name. 'a = mymodule.Developers["name"]' run fine in pycharm.

    ReplyDelete
    Replies
    1. Thanks for your comments. But when i am going to type something may be some extra space comes without my notice as because i am not going to check all code in Python compilers when writing.

      Delete

Post a Comment

Popular Posts

Working with Spark – Spark RDD

Activity Dependencies with Logical AND in ADF