Defining and Importing Python Modules

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Objectives:

  • Defining modules
  • Using the import statement

Note: For this exercise involving modules, it is critically important to make sure you are running Python in a proper environment. You may need to check the value of sys.path if you can't get import statements to work. Ask for assistance if everything seems broken.

Before starting this exercise, first restart your Python interpreter session. If using IDLE, click on the shell window and look for a menu option "Shell > Restart Shell". You should get a message like this:

>>> ##################== RESTART ##################==
>>>

If you are using Unix, simply exit Python and restart the interpreter.

Using the import statement

In previous exercises, you wrote two programs pcost.py and stock.py. Use the import statement to load these programs and use their functionality:

>>> import pcost
44671.15
>>> pcost.portfolio_cost('portfolio2.dat')
19908.75
>>> from stock import Stock
>>> s = Stock('GOOG', 100, 490.10)
>>> s.name
'GOOG'
>>> s.cost()
49010.0
>>>

If you can't get the above statements to work, you might have placed your programs in a funny directory. Make sure you are running Python in the same directory as your files or that the directory is included on sys.path.

Main Module

In your pcost.py program, the last statement called a function and printed out the result. Modify the program so that this step only occurs if the program is run as the main program. Now, try running the program two ways:

First, run the program as main:

python3 pcost.py
44671.15

Next, run the program as a library import. You should not see any output.

>>> import pcost
>>>
âœĻ Check Solution and Practice

Summary

Congratulations! You have completed the Defining Modules lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like