Download presentation
Presentation is loading. Please wait.
Published byElaine Edwards Modified over 9 years ago
1
Chapter 15. Modules Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012
2
Modules Nodules are the highest level program organization unit, which packages program codes and data for reuse Actually, each “file” is a module (Look into Lib in Python)
3
Why Use Modules? Modules provide an easy way to organize components into a system, by serving as packages of names Modules have at least three roles: 1. Code Reuse 2. Implementing shared services or data 3. Make everything “lives” in a Module
4
Module Creation To define a module, use your text editor to type Python code into a text file You may create some functions or variables in that file You can call modules anything, but module filenames should end in.py suffix
5
Modules Usage Clients can use the module file we just wrote by running “import” statement >>> import math >>> import random >>> import module1 # assume this is the file name we saved
6
Modules examples We will create two modules: module1 and module2 module2 will import data and functions from module1
7
module1.py print “First line of module1” def print_out(aa): print aa*3 x=1 y=2
8
module2.py print “First line of module2” import module1 module1.print_out(“Hello World!! ”) # Use module1’s function print module1.x, module1.y # Reference module1’s variable x=10 y=20 print x, y
9
module2 output The result of execute this program is: Hello World!! Hello World!! Hello World!! 1 2 10 20
10
module3.py You may import as many modules as you like, for example: import module1 import module2 print module1.x print module2.x The result of execute this program is: 1 10
11
Important Notice Import Happen Only ONCE If you try to import a module for the second time, Python will NOT execute it
12
Class Practice Create two modules, each module has two functions and two variables Create a third program which calls all functions and prints all variables in module1 and module2 you created
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.