Skip to main content

Section 3.3 Using Existing Code and Libraries

45 minutes
Quick Links: 3.3.1, 3.3.2, 3.3.3, 3.3.4
We can use existing code written by other programmers to help us write programs more quickly and efficiently. For example, we have been using the Turtle library to draw shapes and patterns. The Turtle library is a collection of code that allows us to use the turtle graphics system in our programs.

Subsection 3.3.1 Libraries

A library is a collection of code written by other programmers that we can use in our own programs. Libraries have existing code that can quickly add functionality to our programs without having to write everything ourselves.
In Python, you can import libraries like random or turtle and then use the functions they provide. Single python files that are imported in are called modules, and a folder of these Python files is called a package. Libraries can be collections of modules or packages.
import random
# We can now use the randint() function from the random library
number = random.randint(1, 10)

import turtle
# We can now use the turtle library to draw shapes
turt = turtle.Turtle()
turt.forward(100)
Libraries often have documentation that explains how to use the code and what each function does. For example, https://docs.python.org/3/library/turtle.html#turtle-methods explains every function in the Turtle library. Unfortunately, not all of the Python Turtle functions work in this ebook, because it uses a browser implementation of Python.

Activity 3.3.1.

Look up the function home() in the Turtle documentation https://docs.python.org/3/library/turtle.html#turtle-methods and try using it below. Then, find another Turtle function that you haven’t used before and try it below. Not all functions will work in this ebook, unfortunately, so keep trying different ones until you find one that works.
We can also package our code into modules and packages for easier reuse. We can also include existing code from other sources, including Gen AI. When including code from other sources, it is important to check the license and to give credit to the original creator.

Activity 3.3.2.

What is the purpose of libraries in programming?
  • To write new code from scratch
  • Incorrect. Libraries allow you to use code written by others.
  • To use code written by others to quickly add functionality to our programs
  • Correct! Libraries let you use code written by others to add functionality to your programs.
  • To create programming languages
  • Incorrect. Libraries are defined in a programming language.
  • To compile code
  • Incorrect. Libraries are not for compiling code.

Subsection 3.3.2 Application Programming Interfaces (APIs)

An application programming interface (API) is the set of rules or specification that specifies how to use a library or software component. These rules are spelled out in the library documentation. The API describes what inputs are accepted and what output is returned.

Activity 3.3.3.

Which statement best describes an API?
  • A collection of reusable code.
  • Incorrect. A library is a collection of reusable code. An API describes how software can be used.
  • A Python file containing functions.
  • Incorrect. A Python file containing reusable code is a module. An API describes how software can be used.
  • A set of rules that specifies how software can be used by other software.
  • Correct! An API specifies how software can be used, including what inputs are accepted and what outputs may be returned.
  • A website where programmers download code.
  • Incorrect. An API is not a website. It is a set of rules or specifications for how software can interact.
For example, the following documentation describes the API for the math function isqrt in the Python math module https://docs.python.org/3/library/math.html#math.isqrt:
math.isqrt(n)
Return the integer square root of the nonnegative integer n. 
This is the floor of the exact square root of n, or equivalently the greatest integer a 
such that aΒ² <= n.

Activity 3.3.4.

The documentation for math.isqrt() says:
math.isqrt(n)
Return the integer square root of the nonnegative integer n.
Which function call correctly uses this math library function?
  • math.isqrt()
  • No. The function requires a nonnegative integer as an input.
  • math.isqrt(25)
  • Correct! The function requires a nonnegative integer, and 25 is a valid input.
  • math.isqrt("25")
  • No. "25" is a string, not an integer. The documentation specifies that the input should be a nonnegative integer.
  • math.isqrt(25, 5)
  • No. The documentation shows that isqrt() accepts one input, n, not two inputs.
Many web service or platforms, for example Google Maps, Youtube, Wikipedia, etc. have APIs that allow access to their service for programmers. This simplifies complex programming tasks and allows communication between different programs. For example, you can use the Google Maps API to embed a map in an app that you are creating.
We can often see a web platform’s API in action while using the platform. For example, go to https://www.google.com/maps and search for a location. Notice how the url (web address) changes. For example, if you search for "Philadelphia", the url changes to https://www.google.com/maps/place/Philadelphia followed by other geographic information, but just the city name is enough to get the map to show Philadelphia. This is an example of a web API in action. We now know the rule that we can take the base url and add "place/cityname" to get a map of that city. Try just changing the url to find the map of another city, for example Chicago.

Activity 3.3.5.

As you explore the map of Philadelphia in Google Maps and Zoom into level 15, you see the url https://www.google.com/maps/place/Philadelphia,+PA/@40.002498,-75.0129578,15z. Following the API rules of that url, what url would you use to get a map of Chicago at Zoom level 11?
When selecting libraries or existing code segments, it’s important to consider the following factors:
  • Does the library or code segment fit the program’s purpose and user needs?
  • Is it compatible with the programming environment?
  • Does it come from a trustworthy source?
  • Is it licensed for reuse?
It is also important to cite the sources of any libraries or code segments you use in the comments of your code, and to test it.
If you were creating a calculator app and wanted to have a square root function, you could use the sqrt function from the Python math module. You would first look at its documentation at https://docs.python.org/3/library/math.html#math.sqrt to understand how to use it. After using it in your code, you would need to test it to make sure it works as expected on typical inputs and boundary cases, for example with positive numbers, zero, and negative numbers. The square root of a negative number is not defined in the real number system, so you would expect that to give an error.

Activity 3.3.6.

Use the sqrt function from the Python math module to find the integer square root of a number. Test it with positive numbers, zero, and negative numbers.
After testing with a negative number, comment that line and run again to get all of the points for this activity.

Activity 3.3.7 sqrt Test Plan.

Activity 3.3.8.

Why should you test code from a library or other existing code after adding it to your program?
  • Library code is always correct.
  • Incorrect. Library functions are generally designed to work correctly, but you should still test them in your program.
  • Testing makes it faster.
  • Incorrect. Testing does not make the code run faster.
  • The code may behave differently than you expected.
  • Correct! Testing helps you make sure that the reused code works as expected in your program.
  • It won’t work without testing.
  • Incorrect. It will probably work, but you should still test it to make sure.

Subsection 3.3.3 API Project

In this project, you will use an API For a web service called https://dog.ceo/dog-api which provides free dog images by breed. In the documentation, https://dog.ceo/dog-api/documentation/random, you can find the url (web address) for fetching random dog images. You can also try it in your browser to see that https://dog.ceo/api/breeds/image/random returns some text like {"message":"https://images.dog.ceo/breeds/german-shepherd/n02106662_16342.jpg","status":"success"} and if we paste the embedded image link into a browser, we can see the image that it returns https://images.dog.ceo/breeds/german-shepherd/n02106662_16342.jpg. Try running the active code below to see the random images that it returns which is displayed in the web page using a hidden showImage function.
Now, take a look at the documentation for showing random dog images of a certain breed at https://dog.ceo/dog-api/breeds-list. Pull down the menu to see different breeds.
Let’s use this API to fetch images of a specific dog breed that the user chooses. First, create a list of at least 5 dog breeds that are in the API. Then, use a loop to print the list of dog breeds with their index number. Then, ask the user to input the index number of the dog breed they want to see. Finally, use the API to fetch a random image of that breed and display it on the web page using the showImage function.

Project 3.3.9 Dog API Project.

Run the code below to see a random dog image from the dog API.
Then, change it to show different breeds.
  1. Create a list of at least 5 dog breeds that are in https://dog.ceo/dog-api/breeds-list.
  2. Use an indexed for loop to print the list of dog breeds with their index number.
  3. Ask the user to input the index number of the dog breed they want to see.
  4. Use the breeds list and the user’s index input to save the selected breed name.
  5. Use the selected breed name to fetch a random image using the APIString "https://dog.ceo/api/breed/" + breed + "/images/random"
  6. Change the function apiDog and its function call to have the selected breed as an argument

Activity 3.3.10 Data and API Abstraction Reflection.

Consider the list and the API used in your project code above.
  1. Explain how the list uses data abstraction to manage complexity in your program.
  2. How easy or difficult would it be to add more breeds to your program?
  3. How did the API help to quickly add more functionality to your program?
  4. How did you use the API? What rules or structure of the API did you follow to show the correct images?

Subsection 3.3.4 Vocabulary Review

Activity 3.3.11.

You have attempted of activities on this page.