Importing Modules And Using Functions In Python
A beginner’s Guide
In this lesson I introduce the import command.
Here’s what we have accomplished so far.
We learned that a module is just a file with python code. We created a module called hello_world that contained a simple command. We turned that simple command into a function and we learned how to call that function from inside our module.
When you downloaded Python it came with many modules containing useful functions. We will be importing some of theses modules and using functions from them. The process of using these useful functions is identical to what we are doing with the useless function that we are going to play with today.
We are now going to create another module that will call our pr_hworld function from our hello_world module.
Before we call the function we have to import it. The first line in our new module will be
import hello_worldTo use the function in our first module we might try just typing the name of the function.
import hello_world
pr_hworld ()It does not work. The computer says that it does not recognise pr_hworld (). We have to tell it where pr_hworld() came from. When we called the function from the inside the module that created it we did not have to import it or identify where it came from but this is a new module.
Try this.
import hello_world
hworld.pr_world ()Once again we see Hello World! printed on the screen. I know this is getting a bit silly. I promise that we will do more interesting stuff soon.
In addition to the simple import command there are a few other options.
import hello_world as hwfrom hello_world import pr_hworld, another_functionImport hello_world as hw
Allows you to substitute an abbreviation or shorter form
import hello_world as hw
hw.pr_world)()from hello_world import pr_hworld
This allows you to list one or more functions that you intend to use when you import the module and you won’t have to type in the source.
from hello_world import pr_world
pr_world()Jim McAulay🍁 says, “ When a chameleon can’t change its colours it is called a reptile dysfunction”
45__46
13__11





