Non-Programmer's Tutorial for Python 3/Using Modules

From Wikibooks, open books for an open world
Jump to: navigation, search

Here's this chapter's typing exercise (name it (import actually looks for a file named and reads it in. If the file is named and it sees a "import calendar" it tries to read in itself which works poorly at best.)):

import calendar
year = int(input("Type in the year number: "))

And here is part of the output I got:

Type in the year number: 2001


       January                  February                    March      

Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
1  2  3  4  5  6  7                1  2  3  4                1  2  3  4     
8  9 10 11 12 13 14       5  6  7  8  9 10 11       5  6  7  8  9 10 11
15 16 17 18 19 20 21      12 13 14 15 16 17 18      12 13 14 15 16 17 18     
22 23 24 25 26 27 28      19 20 21 22 23 24 25      19 20 21 22 23 24 25     
29 30 31                  26 27 28                  26 27 28 29 30 31        

(I skipped some of the output, but I think you get the idea.) So what does the program do? The first line import calendar uses a new command import. The command import loads a module (in this case the calendar module). To see the commands available in the standard modules either look in the library reference for python (if you downloaded it) or go to If you look at the documentation for the calendar module, it lists a function called prcal that prints a calendar for a year. The line calendar.prcal(year) uses this function. In summary to use a module import it and then use module_name.function for functions in the module. Another way to write the program is:

from calendar import prcal

year = int(input("Type in the year number: "))

This version imports a specific function from a module. Here is another program that uses the Python Library (name it something like (press Ctrl and the 'c' key at the same time to terminate the program):

from time import time, ctime

prev_time = ""
while True:
    the_time = ctime(time())
    if prev_time != the_time:
        print("The time is:", ctime(time()))
        prev_time = the_time

With some output being:

The time is: Sun Aug 20 13:40:04 2000
The time is: Sun Aug 20 13:40:05 2000
The time is: Sun Aug 20 13:40:06 2000
The time is: Sun Aug 20 13:40:07 2000

Traceback (innermost last):
 File "", line 5, in ?
    the_time = ctime(time())


The output is infinite of course so I cancelled it (or the output at least continues until Ctrl+C is pressed). The program just does an infinite loop (True is always true, so while True: goes forever) and each time checks to see if the time has changed and prints it if it has. Notice how multiple names after the import statement are used in the line from time import time, ctime.

The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.


Rewrite the program from section Decisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.


Rewrite the program from section Decisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.

from random import randint
number = randint(0, 99)
guess = -1
while guess != number: 
    guess = int(input ("Guess a number: "))
    if guess > number:
        print("Too high")
    elif guess < number:
            print("Too low")
print("Just right")

Other modules[edit]

Sometimes you want to use a python module that does not come with the Python installation. You can also import those, but you have to have them installed on your computer.

Creating your own module[edit]

When python reads the import command, it first checks files in your directory, then site-packages or pre installed modules. To make your own module, just create a .py file in the current directory and use the command:

import module

This will try to import the file from your current directory and if not found, from site-packages and prepackaged modules. Changing module to the name of the .py file you created will import that file.

However, when it imports the module, it will basically start the file as a program, so any code on there will be run. You want to group all code into functions.

The __name__ == __main__ trick[edit]

In python, the variable __name__ will give you the current name of the program. If a module you import prints the __name__ variable, then it will print the name of the module. If the current file prints the __name__ variable, it will print __main__, to show it is the main program.

If an if statement checks the name variable and runs code if the program is main, it can bypass the unintentional run problem created when a module is imported. Say for example you have a file, which runs some code. It also has a function you want to use in another program. However, you only want the function, not to run the code. By setting up the code below, it will only run the code if it is the file that was clicked on or started, not if it was imported.

if __name__ == '__main__':

In this instance, if the file is run but not imported, it will run the pass command. You can replace the pass command with the code you want to be run when not imported. Just remember to indent the code.

The pip module[edit]

The pip module is a module that comes with the python installation and acts as a module downloader/manager. You can download other modules from the internet with pip.

The pip module is not used in the python interpreter, but is run through the command line. To use it, open up your command line interpreter (for Windows it is Command Prompt, for Mac/Linux it is Terminal) and type in the following code:

py3 -m pip install module

or the alternate code

pip install module

This will try to download and install module from the user-submitted python modules database. Module can be changed to the name of the module.

Non-Programmer's Tutorial for Python 3
 ← Dictionaries Using Modules More on Lists →