python code
The square of x is 100
Mathematics 204 University of Liberia (Math 204)
2026-03-28
We’ll start with Python’s workhorse data structures: tuples, lists, dictionaries, and sets.
Then, we’ll discuss creating your own reusable Python functions.
Finally, we’ll look at the mechanics of Python file objects and interacting with your local hard drive.
Python Basics | f-string
An f-string is a special string that is created by prefixing the first string-delimiter with the letter f
Any part of an f-string contained within curly braces { } will be evaluated before the string is used.
Python Basics | Tuple
A tuple is a fixed-length, immutable sequence of Python objects which, once assigned, cannot be changed.
The easiest way to create one is with a comma-separated sequence of values wrapped in parentheses ( ):
Example 1.1.1 | Tuple
Example 1.1.3. | More on Tuples
Python Basics | Lists
In contrast with tuples, lists are variable length and their contents can be modified in place.
Lists are mutable.
You can define them using square brackets [ ] or using the list type function.
Python Basics | Lists
Adding and removing elements | Lists
Python Basics | Lists
Python Basics | Lists
Concatenating and combining | Lists
Sorting | Lists
Slicing | Lists
Slicing | Lists
Slicing | Lists
Python Basics | Dictionary
The dictionary or dict may be the most important built-in Python data structure.
A dictionary stores a collection of key-value pairs, where key and value are Python objects.
Each key is associated with a value so that a value can be conveniently retrieved, inserted, modified, or deleted given a particular key.
Python Basics | Dictionary
Python Basics | Dictionary
Python Basics | Set
A set is an unordered collection of unique elements.
A set can be created in two ways: via the set function or via a set literal with curly braces.
Python Basics | Union of Sets
The union of these two sets is the set of distinct elements occurring in either set.
This can be computed with either the union method or the | binary operator:
Python Basics | Intersection of Sets
The intersection contains the elements occurring in both sets.
The & operator or the intersection method can be used:
Loops and Conditionals | The for … in Statements
The for…in compound statement takes a variable after the for keyword.
This variable will hold the current iteration value.
After the in keyword there needs to be an iterable object, which is any object that can be iterated over.
The typical one we will use is the range object that we introduced:
Loops and Conditionals | The for … in Statements
Loops and Conditionals | The for … in Statements
When iterating over objects like a list, it is often helpful to keep track of the iteration index.
One easy way to do this is to use the enumerate() function that returns a tuple of the current iteration index and the item:
Loops and Conditionals | The for … in Statements
We can nest ‘for’ statements, which means that one for statement is inside of another for statement.
For each iteration of the outer loop, the inner loop will run through all its iterations:
Loops and Conditionals | if Statements
More generally, an if statement may also have elif and else clauses.
Elif is short for “else if”, and these headers act like if headers but will be evaluated only if the above if or elif headers did not have their conditions satisfied.
There can only be one else clause, and its suite will be executed if the if and elif clauses did not have their conditions satisfied.
Loops and Conditionals | if Statements
Example 1.1.6 | if Statements
Example 1.1.7 | if Statements
Loops and Conditionals | while Statements
A while loop combines looping and a conditional statement for determining whether looping should continue.
The loop will continue as long as the condition specified in the while statement is satisfied:
Python Basics | Functions
Functions are the primary and most important method of code organization and reuse in Python.
Functions are declared with the def keyword.
A function contains a block of code with an optional use of the return keyword:
Functions | Generator
A generator is a convenient way, similar to writing a normal function, to construct anew iterable object.
Generators can return a sequence of multiple values
To create a generator, use the yield keyword instead of return in a function:
Vectors provide a way to collect and operate on multiple pieces of numerical data.
In this chapter, we define vectors and introduce different ways to visualize vector data. Then we introduce the most common vector operations and their properties.
The chapter ends with a discussion of vector projection, which introduces concepts of how we can approximate a vector as a scaled version of another vector.
Introduction to Vectors | vectors, order, scalar
vector: an ordered collection of numbers that has an accompanying set of mathematical operations.
order: the number of axes used to index the contents of a mathematical object, such as a vector, matrix, or tensor.
scalar: a single numerical value.
vectors, order, scalar
Vectors are usually represented mathematically as a column of numbers enclosed in large square brackets, like \[\textbf{u} = \begin{bmatrix} 0.75 \\ -1 \\ 1.75\\ 2.5 \end{bmatrix}\]
To save space, we can also write a column vector like \[\textbf{u} = \begin{bmatrix} 0.75 & -1 & 1.75 & 2.5 \end{bmatrix}^T\]
where the superscript\(^T\) indicates that the vector should be “transposed” from a row to a column.
Example 2.1 | Vector in NumPy
vectors, order, scalar
Component (vector) | Element (vector)
Example 2.2 | Accessing a Component
Example 2.3 | NumPy Indexing by Range
vectors, order, scalar
Vectors are often visualized as displacements from a point, meaning an indication of movement from some starting point to an ending point.
If no starting point is given, then the displacement is measured from the origin.
One of the most common ways to illustrate a vector is the use of 2-vectors.
To illustrate 2-vectors, draw each 2-vector as an arrow from the origin to the coordinates given in the vector.
This is a special case of a quiver plot:
Visualizing Vectors | Quiver Plot
Quiver Plot: a (two-dimensional) plot that illustrates one or more vectors as arrows that are typically specified by a location, which determines the coordinates of the tail of the vector, and some specification of the direction and magnitude of the vector.
If no location is provided, then the origin (0, 0) is used.
Example 1.2.1 | Plotting a Vector with plotvecR( )
Visualizing Vectors | Head and Tail
Tail (vector): the tail of a vector is the starting point of a vector (the initial point from which the displacement is measured).
Head (vector): the head of a vector is the ending point of a vector (the point at which the vector terminates after the specified displacement from the tail)
Example 1.2.2 | Plotting Two Vectors with Tails at the Origin
Vectors are used in many different ways.
Below are some of the ways that vectors are used, along with an example of each type of use:
Multi-dimensional numerical data
We often represent a data set as a table.
For instance, each row may represent one data point, and each column may represent one feature.
If all of the data features are numeric or encoded as numerical values, then we can use vectors to represent such data in different ways.
Example 1.3.1 | Multi-dimensional numerical data
HTIN4: A computed variable that lists height in inches
WEIGHT2: The reported weight in pounds.
Multi-dimensional numerical data
Because the data occupies a two-dimensional table, we can decompose it into vectors in two different ways:
we can treat each row (i.e., data point) as a vector or
each column (i.e.,feature) as a vector.
Example 1.3.2 | Multi-dimensional numerical data
import pandas as pd
from plotvec import plotvec
# I use a for loop to iterate over the first 50 rows and call plotvec() for each one:
brfss = pd.read_csv('/Users/calvina.gaye/Downloads/Quarto2026/MATH204UL2025_26S2/mdata1.csv')
for i in range(50):
plotvec(brfss.iloc[i], color_offset=2*i, square_aspect_ratio=False, newfig=False)
plt.xlim(0,80)
plt.ylim(0,350)
plt.xlabel('Height (in)')
plt.ylabel('Weight (lbs)')Text(0, 0.5, 'Weight (lbs)')
Example 1.3.2 | Major takeaways
Do you notice any trend the arrow?
All arrows point up and to the right
Most arrows point in the same general direction
General trend by intuition: taller people are more likely to be heavier than shorter people.
Visualizing more data as points | Scatter Plot
A better approach to visualize more numerical data is
A scatter plot takes a sequence of two-dimensional data points \((x_0, y_0), (x_1, y_1) \dots, (x_{n-1}, y_{n-1})\) and plots symbols (called markers) that represent the locations of the points in a rectangular region of a plane.
Example 1.3.3 | Scatter Plot
Visualizing more data as points | Time-series data
Time-series data: data that is collected over time, usually at regular intervals.
Each data point is associated with a timestamp indicating when the data was collected.
Example 1.3.4 | Annual Temp Data for Liberia
| Entity | Code | Year | TempAnomaly | |
|---|---|---|---|---|
| 0 | Liberia | LBR | 1940 | -0.922306 |
| 1 | Liberia | LBR | 1941 | -0.904504 |
| 2 | Liberia | LBR | 1942 | -1.037940 |
| 3 | Liberia | LBR | 1943 | -1.083066 |
| 4 | Liberia | LBR | 1944 | -0.992378 |
Visualizing Liberia Temperature Anomaly | Time-Series Plot
import pandas as pd
import polars as pl
import matplotlib.pyplot as plt
from plotnine import *
libtemp = pd.read_csv('/Users/calvina.gaye/Downloads/Quarto2026/Python_venv2026/ULSem2_202526/annual_temp_anom/ave_annual_surface_temp.csv')
plt.scatter(libtemp['Year'], libtemp['Temperature'], 15)
plt.xlabel('Year')
plt.ylabel('Annual Surface Temperature ($\circ$C)')Text(0, 0.5, 'Annual Surface Temperature ($\\circ$C)')
import pandas as pd
import polars as pl
import matplotlib.pyplot as plt
from plotnine import *
libtemp = pl.read_csv('/Users/calvina.gaye/Downloads/Quarto2026/Python_venv2026/ULSem2_202526/annual_temp_anom/ave_annual_surface_temp.csv')
temp = ggplot(libtemp, aes(x="Year", y="Temperature")) + geom_point() + labs(title = "Liberia Average Annual Surface Temperature", x = "Year (1940 - 2025)", y = "Annual Surface Temperature", caption="Data source: Contains modified Copernicus Climate Change Service information (2026)")
tempScatter Plot and Time Series | Major takeaways
Scatter Plot
Time Series
Visualizing Vectors | Distributional Data
Vectors may be used to indicate distributions or allocations across categories.
For example, an investor’s current net worth across different categories (such as stocks, bonds, and real estate) can be represented as a vector.
Visualizing Vectors | Distributional Data
shape: (5, 4)
┌─────────────────────────┬────────┬──────────┬─────────────┐
│ a ┆ Symbol ┆ Weight ┆ Price │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ f64 │
╞═════════════════════════╪════════╪══════════╪═════════════╡
│ Unitedhealth Group Inc ┆ UNH ┆ 8.315803 ┆ 606.79 │
│ Goldman Sachs Group Inc ┆ GS ┆ 8.27737 ┆ 605.5 │
│ Home Depot Inc ┆ HD ┆ 5.884052 ┆ 429.52 │
│ Microsoft Corp ┆ MSFT ┆ 5.748436 ┆ 427.99 │
│ Caterpillar Inc ┆ CAT ┆ 5.568073 ┆ 407.83 │
└─────────────────────────┴────────┴──────────┴─────────────┘
Distributional Data | Bar Graph
Visualizing Vectors | Distributional Data
Vectors may be used to indicate distributions or allocations across categories.
For example, an investor’s current net worth across different categories (such as stocks, bonds, and real estate) can be represented as a vector.
import pandas as pd
import polars as pl
from great_tables import GT
animals_pd = pd.read_csv("polars/data/animals.csv", sep=",", header=0)
animals_pl = pl.read_csv("polars/data/animals.csv", separator=",", has_header=True)
animals_pd = animals_pd.drop(columns=["habitat", "diet", "features"])
animals_pd| animal | class | lifespan | status | weight | |
|---|---|---|---|---|---|
| 0 | dolphin | mammal | 40 | least concern | 150.0 |
| 1 | duck | bird | 8 | least concern | 3.0 |
| 2 | elephant | mammal | 60 | endangered | 8000.0 |
| 3 | ibis | bird | 16 | least concern | 1.0 |
| 4 | impala | mammal | 12 | least concern | 70.0 |
| 5 | kudu | mammal | 15 | least concern | 250.0 |
| 6 | narwhal | mammal | 40 | near threatened | NaN |
| 7 | panda | mammal | 20 | vulnerable | 100.0 |
| 8 | polar bear | mammal | 25 | vulnerable | 720.0 |
| 9 | ray | fish | 20 | NaN | 90.0 |
Sir Calvin A. Gaye \(\quad \quad \quad \quad \quad \quad\) Elementary Linear Algebra \(\quad \quad \quad \quad \quad\) Semester 2 2025/26