Modules are simply files with the .py extension, containing code that can be imported into another program.
In doing this, we can build up a code library that contains a set of functions that you want to include when developing larger applications.
In this section, we'll take a look at how to create modules and include them in our Python programs.
Importing Modules
math – Mathematical functions
turtle – Turtle graphics
tkinter – GUI interface toolkit
pygame – Toolkit for creating games and other multimedia applications.
Turtle graphics operate much like a drawing board, in which you can execute various commands to move a turtle around. We can use functions like forward() and right() . The turtle will travel along the path that you define using these functions, leaving a pen mark behind it.
turtle is the name of the module we imported earlier, and forward() is a function defined within the module.
Let’s put this into a program. In the following, we have our import statement to import all the turtle graphics modules. Below that, we have a statement that moves the turtle forward and one to finish the program.
This will move the turtle 100 pixels forward.
Here, we can see the output to the program: the turtle has moved 100 pixels to the right.
We can complete the program to draw a square.
Try out some of the other turtle commands .
Creating Your Own Modules
You can declare and store your functions in a separate file and import them into your main program.
All function definitions can be stored in a file, for example, myfunctions.py.
The main program could be called functionmain.py. At the top of the main program script, you’ll need to import your functions stored in the other file (myfunctions.py). Strip off the file extension (.py).
This is called a module . Any functions declared will be included in the main program. You can include these functions in any program you need to. This makes maintenance easier.
Now, to call any functions from that module, you need to specify the module name followed by the function name.
Lab Exercises
- 1.
Write a function that accepts a number from the user and uses a function to square the number and then return the result.
- 2.
Save this file as a module.
- 3.
Import the module you just created into a new program.
- 4.
Call the function in the module.
- 5.
Create a new program and import the turtle graphics module.
- 6.
Experiment with drawing different shapes using some of the turtle graphics methods.
- 7.
Use the turtle commands to draw some shapes.
Summary
Modules are simply files with the .py extension, containing code that can be imported into another program.
You can import modules using the import keyword.
When we import a module, we are making it available in our program as a separate namespace. This means that we have to refer to the function in a particular module using the dot notation.