0% found this document useful (0 votes)
19 views

Modules

Uploaded by

deepgyan780
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Modules

Uploaded by

deepgyan780
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python Module

What is a Module?

 Consider a module to be the same as a code library.


 A file containing a set of functions you want to include in your application.
 Create a Module

 To create a module just save the code you want in a file


with the file extension .py:
 def greeting(name):
print("Hello, " + name)

 Save this code in a file named mymodule.py


:

Use a Module

 Now we can use the module we just created, by using


the import statement.
 Import the module named mymodule, and call the greeting function:
 import mymodule

mymodule.greeting("Jonathan")
 Note: When using a function from a module, use the
syntax: module_name.function_name.
Variables in Module

 The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):

 Save this code in the file mymodule.py


 person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Cont.

 Import the module named mymodule, and access the person1 dictionary:
 import mymodule
a = mymodule.person1["age"]
print(a)
:

Re-naming a Module

 You can create an alias when you import a module, by


using the as keyword
 Create an alias for mymodule called mx:
 import mymodule as mx
a = mx.person1["age"]
print(a)
Import From Module

 You can choose to import only parts from a module, by


using the from keyword
 Import only the person1 dictionary from the module:
 from mymodule import person1

print (person1["age"])

You might also like