A library is a collection of code for functions and classes. Often, these
libraries are written by someone else and brought into the project so that
the programmer does not have to “reinvent the wheel.” In Python the term used
to describe a library of code is module.

By using importarcade and importrandom, the programs created so far have
already used modules. A library can be made up of multiple modules that can be
imported. Often a library only has one module, so these words can sometimes be
used interchangeably.

Modules are often organized into groups of similar functionality. In this class
programs have already used functions from the math module, the random module,
and the arcade library. Modules can be organized so that individual modules
contain other modules. For example, the arcade module contains submodules for
arcade.key, and arcade.color.

Modules are not loaded unless the program asks them to. This saves time and
computer memory. This chapter shows how to create a module, and how to import
and use that module.

There are three major reasons for a programmer to create his or her own
libraries:

It breaks the code into smaller, easier to use parts.

It allows multiple people to work on a program at the same time.

The code written can be easily shared with other programmers.

Some of the programs already created in this book have started to get rather
long. By separating a large program into several smaller programs, it is
easier to manage the code. For example, in the prior chapter’s sprite example,
a programmer could move the sprite class into a separate file. In a complex
program, each sprite might be contained in its own file.

If multiple programmers work on the same project, it is nearly impossible to
do so if all the code is in one file. However, by breaking the program into
multiple pieces, it becomes easier. One programmer could work on developing
an “Orc” sprite class. Another programmer could work on the “Goblin” sprite
class. Since the sprites are in separate files, the programmers do not run
into conflict.

Modern programmers rarely build programs from scratch. Often programs are
built from parts of other programs that share the same functionality. If
one programmer creates code that can handle a mortgage application form,
that code will ideally go into a library. Then any other program that needs
to manage a mortgage application form at that bank can call on that library.

Yes, this program is not too long to be in one file. But if both the function
and the main program code were long, it would be different. If we had several
functions, each 100 lines long, it would be time consuming to manage that
large of a file. But for this example we will keep the code short for clarity.

We can move the foo function out of this file. Then this file would be left
with only the main program code. (In this example there is no reason to
separate them, aside from learning how to do so.)

To do this, create a new file and copy the foo function into it. Save the
new file with the name my_functions.py. The file must be saved to the same
directory as test.py.

A program might have two library files that need to be used. What if the
libraries had functions that were named the same? What if there were two
functions named print_report, one that printed grades, and one that printed
an account statement? For instance:

So now we can see why this might be needed. But what if you don’t have name
collisions? Typing in a namespace each and every time can be tiresome. You
can get around this by importing the library into the local namespace. The
local namespace is a list of functions, variables, and classes that you
don’t have to prepend with a namespace. Going back to the foo example,
let’s remove the original import and replace it with a new type of import:

This works even without my_functions. prepended to the function call. The
asterisk is a wildcard that will import all functions from my_functions.
A programmer could import individual ones if desired by specifying the
function name.

This example uses a library called OpenPyXL to write an Excel file. It is also
easy to read from an Excel file.
You can install OpenPyXL from the Windows command prompt by typing
pipinstallopenpyxl.
If you are on the Mac or a Linux machine, you can type sudopip3installopenpyxl.

Note

When starting the command prompt, you might need to right-click on it and select “Run as administrator” if
you get permission errors when installing.
And if you are working on a lab computer, you might not have permission to install libraries.

"""Example using OpenPyXL to create an Excel worksheet"""fromopenpyxlimportWorkbookimportrandom# Create an Excel workbookwork_book=Workbook()# Grab the active worksheetwork_sheet=work_book.active# Data can be assigned directly to cellswork_sheet['A1']="This is a test"# Rows can also be appendedforiinrange(200):work_sheet.append(["Random Number:",random.randrange(1000)])# Save the filework_book.save("sample.xlsx")

This example grabs information off a web page.
You can install Beautiful Soup from the Windows command prompt by typing
pipinstallbs4. If you are on the Mac or a Linux machine, you can type
sudopip3installbs4.

"""Example showing how to read in from a web page"""frombs4importBeautifulSoupimporturllib.request# Read in the web pageurl_address="http://simpson.edu"page=urllib.request.urlopen(url_address)# Parse the web pagesoup=BeautifulSoup(page.read(),"html.parser")# Get a list of level 1 headings in the pageheadings=soup.findAll("h1")# Loop through each rowforheadinginheadings:print(heading.text)

Here is an example of what you can do with the third party library “Matplotlib.”
You can install Matplotlib from the Windows command prompt by typing
pipinstallmatplotlib. If you are on the Mac or a Linux machine, you can
type pip3installmatplotlib.

"""This example shows graphing two different serieson the same graph."""importmatplotlib.pyplotaspltx=[1,2,3,4]y1=[1,3,8,4]y2=[2,2,3,3]plt.plot(x,y1)plt.plot(x,y2)plt.ylabel('Element Value')plt.xlabel('Element')plt.show()

"""This shows how to set line style and markers."""importmatplotlib.pyplotaspltx=[1,2,3,4]y1=[1,3,8,4]y2=[2,2,3,3]# First character: Line style# One of '-', '--', '-.', ':', 'None', ' ', "# Second character: color# http://matplotlib.org/1.4.2/api/colors_api.html# Third character: marker shape# http://matplotlib.org/1.4.2/api/markers_api.htmlplt.plot(x,y1,'-ro')plt.plot(x,y2,'--g^')plt.ylabel('Element Value')plt.xlabel('Element')plt.show()

"""Using 'fill' to fill in a graph"""importnumpyimportmatplotlib.pyplotaspltx=numpy.arange(0.0,2.0,0.001)y=numpy.sin(2*numpy.pi*x)plt.plot(x,y)# 'b' means blue. 'alpha' is the transparency.plt.fill(x,y,'b',alpha=0.3)plt.ylabel('Element Value')plt.xlabel('Element')plt.show()

"""Create a pie chart"""importmatplotlib.pyplotasplt# Labels for the pie chartlabels=['C','Java','Objective-C','C++','C#','PHP','Python']# Sizes for each label. We use this to make a percentsizes=[17,14,9,6,5,3,2.5]# For list of colors, see:# https://matplotlib.org/examples/color/named_colors.htmlcolors=['yellowgreen','gold','lightskyblue','lightcoral','darkcyan','aquamarine','rosybrown']# How far out to pull a slice. Normally zero.explode=(0,0.0,0,0,0,0,0.2)# Set aspect ratio to be equal so that pie is drawn as a circle.plt.axis('equal')# Finally, plot the chartplt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=90)plt.show()

"""Create a candlestick chart for a stock"""importmatplotlib.pyplotaspltfrommatplotlib.datesimportDateFormatter,WeekdayLocator,\
DayLocator,MONDAYfrommatplotlib.financeimportquotes_historical_yahoo_ohlc,candlestick_ohlc# Grab the stock data between these datesdate1=(2014,10,13)date2=(2014,11,13)# Go to the web and pull the stock infoquotes=quotes_historical_yahoo_ohlc('AAPL',date1,date2)iflen(quotes)==0:raiseSystemExit# Set up the graphfig,ax=plt.subplots()fig.subplots_adjust(bottom=0.2)# Major ticks on Mondaysmondays=WeekdayLocator(MONDAY)ax.xaxis.set_major_locator(mondays)# Minor ticks on all daysalldays=DayLocator()ax.xaxis.set_minor_locator(alldays)# Format the daysweekFormatter=DateFormatter('%b %d')# e.g., Jan 12ax.xaxis.set_major_formatter(weekFormatter)ax.xaxis_date()candlestick_ohlc(ax,quotes,width=0.6)ax.autoscale_view()plt.setp(plt.gca().get_xticklabels(),rotation=45,horizontalalignment='right')plt.show()

There are many more things that can be done with matplotlib. Take a look at
the thumbnail gallery: