Appendix A: Glossary

Published

2023-08-02

absolute value

The absolute value of a number is its distance from the origin (0), that is, the magnitude of the number regardless of its sign. In mathematics this is written with vertical bars on either side of the number or variable in question. Thus

\begin{align*} |4| &= 4 \\ |-4| &= 4 \end{align*}

and generally,

|x| = \begin{cases} x & x \geq 0 \\ -x & x < 0. \end{cases}

The absolute value of any numeric literal, variable, or expression can be calculated with the Python built-in, abs().

accumulator

An accumulator is a variable that’s used to hold a cumulative result within a loop. For example, we can calculate the sum of all numbers from 1 to 10, thus

s = 0  # s is the accumulator
for n in range(1, 11):
    s += n  # s is incremented at each iteration

adjacent

We say two vertices A, B, in a graph are adjacent if an edge exists in the graph with endpoints A and B.

alternating sum

An alternating sum is a sum which alternates addition and subtraction depending on the index or parity of the term to be summed. For example:

s = 0
for n in range(1, 11):
    if n % 2:    # n is odd
        s -= n   # subtract n
    else:        # n must be even
        s += n   # add n

implements the alternating sum

0 - 1 + 2 - 3 + 4 - 5 + 6 - 7 + 8 - 9 + 10

or equivalently

\sum\limits_{i \: = 0}^{10} (-1)^i \; x_i.

Alternating sums appear quite often in mathematics.

argument

An argument is a value (or variable) that is passed to a function when it is called. An argument is then assigned to the corresponding formal parameter in the function definition. For example, if we call Python’s built-in sum() function, we must provide an argument (the thing that’s being summed).

s = sum([2, 3, 5, 7, 11])

Here, the argument supplied to the sum() function is the list [2, 3, 5, 7, 11]. See: formal parameter.

Most arguments that appear in this text are positional arguments, that is, the formal parameters to which they are assigned depend on the order of the formal parameters in the function definition. The first argument is assigned to the first formal parameter (if any). The second argument is assigned to the second formal parameter, and so on. The number of positional arguments must agree with the number of positional formal parameters, otherwise a TypeError is raised.

See also: keyword argument.

arithmetic mean

The arithmetic mean is what’s informally referred to as the average of a set of numbers. It is the sum of all the numbers in the set, divided by the number of elements in the set. Generally,

\mu = \frac{1}{N} \sum\limits_{i \: = \: 0}^{N-1} x_i.

This can be implemented in Python:

m = sum(x) / len(x)

where x is some list or tuple of numeric values.

arithmetic sequence

An arithmetic sequence of numbers is one in which the difference between successive terms is a constant. For example, 1, 2, 3, 4, 5,  is an arithmetic sequence because the difference between successive terms is the constant, 1. Other examples of arithmetic sequences:

\begin{align*} & 2, 4, 6, 8, 10, \ldots \\ & 7, 10, 13, 16, 19, 22, \ldots \\ & 44, 43, 42, 41, 40, 39, \ldots \\ \end{align*}

Python’s range objects are a form of arithmetic sequence. The stride (which defaults to 1) is the difference between successive terms. Example:

range(3, 40, 3)

when iterated counts by threes from three to 39.

assertion

An assertion is a statement about something you believe to be true. “At the present moment, the sky is blue.” is an assertion (which happens to be true where I am, as I write this). We use assertions in our code to help verify correctness, and assertions are often used in software testing. Assertions can be made using the Python keyword assert (note that this is a keyword and not a function). Example:

assert 4 == math.sqrt(16)

assignment

We use assignment to bind values to names. In Python, this is accomplished with the assignment operator, =. For example:

x = 4

creates a name x (presuming x has not been defined earlier), and associates it with the value, 4.

binary code

Ultimately, all instructions that are executed on your computer and all data represented on your computer are in binary code. That is, as sequences of 0s and 1s.

bind / bound / binding

When we make an assignment, we say that a value is bound to a name—thus creating an association between the two. For example, the assignment n = 42 binds the name n to the value 42.

In the case of operator precedence, we say that operators of higher precedence bind more strongly than operators of lower precedence. For example, in the expression 1 + 2 * 3, the subexpression 2 * 3 is evaluated before performing addition because * binds more strongly than +.

Boolean connective

The Boolean connectives in Python are the keywords and, or, and not. See: Boolean expressions, and Chapter 8 Branching.

Boolean expression

A Boolean expression is an expression with one or more Boolean variables or literals (or variables or literals with truth value), joined by zero or more Boolean connectives. The Boolean connectives in Python are the keywords and, or, and not. For example:

(x1 or x2 or x3) and (not x2 or x3 or x4)

is a Boolean expression, but so is the single literal

True

It’s important to understand that in Python, almost everything has a truth value (we refer to this as truthiness or falsiness), and that Boolean expressions needn’t evaluate to only True or False.

branching

It is through branching that we implement conditional execution of portions of our code. For example, we may wish some portion of our code to be executed only if some condition is true. Branching in Python is implemented with the keywords if, elif, and else. Examples:

if x > 1:
   print("x is greater than one")

and

if x < 0:
   print("x is less than zero")
elif x > 1:
   print("x is greater than one")
else:
   print("x must be between 0 and 1, inclusive")

It’s important to understand that in any given if/elif/else compound statement, only one branch is executed—the first for which the condition is true, or the else clause (if there is one) in the event that none of the preceding conditions is true.

Try/except can be considered another form of branching. See: Exception Handling (Chapter 15).

bug

Simply put, a bug is a defect in our code. I hesitate to call syntax errors “bugs”. It’s best to restrict this term to semantic defects in our code (and perhaps unhandled exceptions which should be handled). In any event, when you find a bug, fix it!

bytecode

Bytecode is an intermediate form, between source code (written by humans) and binary code (which is executed by your computer’s central processor unit (CPU)). Bytecode is a representation that’s intended to be efficiently executed by an interpreter. Python, being an interpreted language, produces an intermediate bytecode for execution on the Python virtual machine (PVM). Conversion of Python source code to intermediate bytecode is performed by the Python compiler.

call (see: invoke)

When we wish to use a previously-defined function or method, we call the function or method, supplying whatever arguments are required, if any. When we call a function, flow of execution is temporarily passed to the function. The function does its work (whatever that might be), and then flow of control and a value are returned to the point at which the function was called. See: Chapter 5 Functions, for more details.

print("Hello, World!")  # call the print() function
x = math.sqrt(2)        # call the sqrt() function

Note: call is synonymous with invoke.

camel case

Camel case is a naming convention in which an identifier composed of multiple words has the first letter of each interior word capitalized. Sometimes stylized thus: camelCase. See: PEP 8 for appropriate usage.

central tendency

In statistics, the arithmetic mean is one example of a measure of central tendency, measuring a “central” or (hopefully) “typical” value for a data set. Another aspect of central tendency is that values tend to cluster around some central value (for example, mean).

comma separated values (CSV)

The comma separated values format (CSV) is a commonly used way to represent data that is organized into rows and columns. In this format, commas are used to separate values in different columns. If commas appear within a value, say in the case of a text string, the value is delimited with quotation marks. Python provides a convenient module—the csv module for reading, parsing, and iterating rows in a CSV file.

command line interface (CLI)

Command line interfaces (abbreviated CLI) are user interfaces where the user interacts with a program by typing commands or responding to prompts in text form, or viewing data and responses from the program in similar format. All the programs in this book make use of a command line interface.

comment

Strictly speaking, comments are text appearing in source code which is not read or interpreted by the language, but instead, is solely for the benefit of human readers. Comments in Python are delimited by the octothorpe, #, a.k.a. hash sign, pound sign, etc. In Python, any text on a given line following this symbol is ignored by the interpreter.

In general, it is good practice to leave comments which explain why something is as it is. Ideally, comments should not be necessary to explain how something is being done (as this should be evident from the code itself).

comparable

Objects are comparable if they can be ordered or compared, that is, if the comparison operators—==, <=, >=, <, >, and != can be applied. If so, the operands on either side of the comparison operators are comparable. Instances of many types can be compared among themselves (any string is comparable to all other strings, any numeric is comparable to all other numerics), but some types cannot be compared with other objects of the same type. For example, we cannot compare objects of type range or function this way. In most cases, objects of different types are not comparable (with different numeric types as a notable exception). For example, we cannot compare strings and integers.

compiler

A compiler is a program which converts source code into machine code, or, in the case of Python, to bytecode, which can then be run on the Python virtual machine.

concatenation

Concatenation is a kind of joining together, not unlike coupling of railroad cars. Some types can be concatenated, others cannot. Strings and lists are two types which can be concatenated. If both operands are a string, or both operands are a list, then the + operator performs concatenation (rather than addition, if both operands were numeric).

Examples:

>>> 'dog' + 'food'
'dogfood'
>>> [1, 2, 3] + ['a', 'b', 'c']
[1, 2, 3, 'a', 'b', 'c']

condition

Conditions are used to govern the behavior of while loops and if/elif/else statements. Loops or branches are executed when a condition is true—that is, it evaluates to True or has a truthy value. Note: Python supports conditional expressions, which are shorthand forms for if/else, but these are not presented in this text.

congruent

In the context of modular arithmetic, we say two numbers are congruent if they have the same remainder with respect to some given modulus. For example, 5 is congruent to 19 modulo 2, because 5 % 2 leaves a remainder of 1 and 19 % 2 also leaves a remainder of 1. In mathematical notation, we indicate congruence with the \equiv symbol, and we can write this example as 5 \equiv 19 \pmod{2}. In Python, the expression 5 % 2 == 19 % 2 evaluates to True.

console

Console refers either to the Python shell, or Python input/output when run in a terminal.

constructor

A constructor is a special function which constructs and returns an object of a given type. Python provides a number of built-in constructors, for example, int(), float(), str(), list(), tuple(), etc. These are often used in Python to perform conversions between types. Examples:

  • list(('a', 'b', 'c')) returns the list: ['a', 'b', 'c'].
  • list('apple') `explodes'' the string and returns the list:[‘a’, ‘p’, ‘p’, ‘l’, ‘e’]`.
  • int(42.1) returns an integer, truncating the portion to the right of the decimal point: 42.
  • int('2001') returns the integer: 2001.
  • float('98.6') returns the float: 98.6.
  • tuple([2, 4, 6, 8]) returns the tuple: (2, 4, 6, 8).

Other constructors include range() and enumerate().

context manager

Context managers are created using the with keyword, and are commonly used when working with file I/O. Context managers take over some of the work of opening and closing a file, or ensuring that a file is closed at the end of a with block, regardless of what else might occur within that block. Without using a context manager, it’s up to the programmer to ensure that a file is closed. Accordingly, with is the preferred idiom whenever opening a file.

Context managers have other uses, but these are outside the scope of this text.

cycle (within a graph)

A cycle exists in a graph if there is more than one path of edges from one vertex to another. We refer to a graph containing a cycle or cycles as cyclic, and a graph without any cycles as acyclic.

delimiter

A delimiter is a symbol or symbols used to set one thing apart from another. What delimiters are used, how they are used, and what they delimit depend on context. For example, single-line and inline comments in Python are delimited by the # symbol at the start and the newline character at the end. Strings can be delimited (beginning and end) with apostrophes, ', quotation marks, ", or triple quotation marks, """. In a CSV file, columns are delimited by commas.

dictionary

A dictionary is a mutable type which stores data in key/value pairs, like a conventional dictionary. Keys must be unique, and each key is associated with a single value. Dictionary values can be just about anything, including other dictionaries, but keys must be hashable. Dictionaries are written in Python using curly braces, with colons used to separate keys and values. Dictionary entries (elements) are separated by commas.

Examples:

  • {1: 'odd', 2: 'even'}
  • {'apple': 'red', 'lime': 'green', 'lemon': 'yellow'}
  • {'name': 'Egbert', 'courses': ['CS1210', 'CS2240', 'CS2250'], 'age': 19}

directory (file system)

A directory is a component of a file system which contains files, and possibly other directories. It is the nesting of directories (containment of one directory within another) that gives a file system its hierarchical structure. The top-level directory in a disk drive or volume is called the root directory.

In modern operating system GUIs, directories are visually represented as folders, and may be referred to as folders.

dividend

In the context of division (including floor division, // and the modulo operator, %), the dividend is the number being divided. For example, in the expression 21 / 3, the dividend is 21.

divisor

In the context of division (including floor division, // and the modulo operator, %), the divisor is the number dividing the dividend. For example, in the expression 21 / 3, the divisor is 3. In the context of the modulo operator and modular arithmetic, we also refer to this as the modulus.

driver code

Driver code is an informal way of referring to the code which drives (runs) your program, to distinguish it from function definitions, constant assignments, or classes defined by the programmer. Driver code is often fenced behind the if statement: if __name__ == '__main__':

docstring

A docstring is a triple-quoted string which includes information about a program, module, function, or method. These should not be used for inline comments. Unlike inline comments, docstrings are read and parsed by the Python interpreter. Example at the program (module) level:

"""
My Fabulous Program
Egbert Porcupine <eporcupi@uvm.edu>
This program prompts the user for a number and
returns the corresponding frombulation coefficient.
"""

Or at the level of a function:

def successor(n_):
    """Given some number, n_, returns its successor. """
    return n_ + 1

dunder

Special variables and functions in Python have identifiers that begin and end with two underscores. Such identifiers are referred to as dunders, a descriptive portmanteau of “double underscore.” Examples include the variable __name__ and the special name '__main__', and many other identifiers defined by the language. These are generally used to indicate visually that these are system-defined identifiers.

dynamic typing / dynamically typed

Unlike statically typed languages (for example, C, C++, Java, Haskell, OCaml, Rust, Scala), Python is dynamically typed. This means that we can rebind new values to existing names, even if these values are of a different type than were bound in previous assignments. For example, in Python, this is A-OK:

x = 1         # now x is bound to a value of type int
x = 'wombat'  # now x is bound to a value of type str
x = [3, 5, 7] # ...and now a list

This demonstrates dynamic typing—at different points in the execution of this code x is associated with values of different types. In many other languages, this would result in type errors.

edge (graph)

A graph consists of vertices (also called nodes) and edges. An edge connects two vertices, and each edge in a graph has exactly two endpoints (vertices). All edges in graphs in this text are undirected, meaning that they have no direction. If an edge exists between vertices A and B, then A is adjacent to B and B is adjacent to A.

empty sequence

The term empty applies to any sequence which contains no elements. For example, the empty string "", the empty list [], and the empty tuple (,)—these are all empty sequences. We refer to these using the definite article (“the”), because there is only one such object of each type. Of note, empty sequences are falsey.

entry point

The entry point of a program is the point at which code begins execution. In Python, the dunder __main__ is the name of the environment where top-level code is run, and thus indicates the entry point. Example:

"""
Some docstring here
"""

def square(x_):
    return x_ * x_

# This is the entry point, where execution of code begins...
if __name__ == '__main__':
    x = float(input("Enter a number: "))
    x_squared = square(x)
    print(f"{x} squared is {x_squared}")

escape sequence

An escape sequence (within a string) is a substring preceded by a \ character, indicating that the following character should be interpreted literally and not as a delimiter. Example: print('The following apostrophe isn\'t a delimiter')

Escape sequences are also used to represent special values that otherwise can’t be represented within a string. For example, \n represents a new line and \t represents a tab.

Euclidean division

This is the kind of division you first learned in primary school, before you learned about decimal expansion. A calculation involving Euclidian division yields a quotient and a remainder (which may be zero). In Python, this is implemented by two separate operators, one which yields the quotient (without decimal expansion), and the other which yields the remainder. These are // (a.k.a. floor division) and % (a.k.a., modulo) respectively.

So, for example, in primary school, when asked to divide 25 by 3, you’d answer 8 remainder 1. In Python:

quotient = 25 // 3   # quotient gets 8
remainder = 25 % 3   # remainder gets 1

evaluate / evaluation

Expressions are evaluated by reducing them to a value. For example, the evaluation of the expression 1 + 1 yields 2. The evaluation of larger expressions proceeds by order of operator precedence or order of function calls. So, for example,

>>> import math
>>> x = 16
>>> y = 5
>>> int(math.sqrt(x) + 4 * y + 1)
25

The call to math.sqrt() is evaluated first (yielding 4.0). The multiplication 4 * y is evaluated next (yielding 20). Then addition is performed (4.0 + 20 + 1, yielding 25.0). Finally, the int constructor is called, and the final evaluation of this expression is 25.

When literals are evaluated, they evaluate to themselves.

exception

An exception is an error that occurs at run time. This occurs when code is syntactically valid, but it contains semantic defects (bugs) or receives unexpected values. When Python detects such an error, it raises an exception. If the exception is not handled, program execution terminates. Python provides a great many built-in exceptions which help in diagnosing errors. Examples: TypeError, ValueError, ZeroDivisionError, etc. Exceptions can be handled using try and except.

exception handling

Exception handling allows the programmer to anticipate the possibility of certain exceptions that might arise during execution and provide a fallback or means of responding to the exception should it arise. For example, we often use exception handling when validating input from the user.

while True:
    response = input("Enter a valid number greater than zero: ")
    try:
        x = float(response)
        if x > 0:
            break
    except ValueError:
        print(f"Sorry I cannot convert {response} to a float!")

Exception handling should be as limited and specific as possible. For example, you should never use a bare except: or except Exception:.

Some types of exception, for example NameError should never be handled, as this would conceal a serious programming defect which should be addressed by revising code.

expression

An expression is any syntactically valid code that can be evaluated, that is, an expression yields a value. Expressions can be simple (for example, a single literal) or complex (composed of literals, variables, operators, function calls, etc).

falsey

When used as conditions or in Boolean expressions, most everything in Python has a truth value. If something has a truth value that is treated as if it were false, we say such a thing is falsey. Falsey things include (but are not limited to) empty sequences, 0, and 0.0.

Fibonacci sequence

The Fibonacci sequence is a sequence of natural numbers starting with 0, 1, in which each successive element is the sum of the two preceding elements. Thus the Fibonacci sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, The Fibonacci sequence gets its name from Leonardo of Pisa (c. 1170–c. 1245 CE) whose nickname was Fibonacci. The Fibonacci sequence was known to Indian mathematicians (notably Pingala) as early as 200 BCE, but history isn’t always fair about naming these things.

file

A file is a component of a file system that’s used to store data. The computer programs you write are saved as files, as are all the other documents, programs, and other resources you may have on your computer. Files are contained in directories.

floating-point

A floating-point number is a number which has a decimal point. These are represented differently from integers. Python has a type, float which is used for floating-point numbers.

floor division

Floor division calculates the Euclidean quotient, or, if you prefer, the largest integer that is less than or equal to the result of floating-point division. For example, 8 // 3 yields 2, because 2 is the largest integer less than 2.666(which is the result of 8 / 3).

floor function

The floor function returns the largest integer less than or equal to the argument provided. In mathematical notation, we write

\lfloor x \rfloor

and, for example \lfloor 6.125 \rfloor = 6.

Python implements this function in the math module. Example: math.floor(6.125) yields 6.

flow chart

A flow chart is a tool used to represent the possible paths of execution and flow of control in a program, function, method, or portion thereof. See: Appendix E: Flow Charts.

format specifier

Format specifiers are used within f-string replacement fields to indicate how the interpolated content should be formatted, for example, indicating precision of floating-point numbers; aligning text left, right or center, etc. There is a complete “mini-language” of format specifiers. Within the replacement field, the format specifier follows the interpolated expression, separated by a colon. Format specifiers are optional.

folder (see: directory)

Folder is synonymous with directory.

f-string

f-string is short for formatted string literal. f-strings are used for string interpolation, where values are substituted into replacement fields within the f-string (with optional formatting specifiers). The syntax for an f-string requires that it be prefixed with the letter “f”, and replacement fields appear within curly braces. For example, f"The secret number is {num}." In this case, the replacement field is {num}, and the string representation of the value associated with the identifier num is substituted into the string. So, if we had num = 42, then this string becomes “The secret number is 42.”

function

In Python, a function is a named block of code which performs some task or returns some value. We distinguish between the definition of a function, using the keyword def, and calls to the function, which result in the function being executed and then returning to the point at which it was called. Functions may have zero or more formal parameters. Formal parameters receive arguments when the function is called.

All Python functions return a value (the default, if there is no explicit return statement, is for the function to return None).

See: Chapter 5 Functions.

graph

A graph consists of a set of vertices and a set of edges. Trivially, the empty graph is one with no vertices and thus no edges. A graph with two or more vertices may include edges (assuming we exclude self-edges which is common). An edge connects two vertices.

Graphs are widely used in computer science to represent networks of all kinds as well as mathematical and other objects.

graphical user interface

A graphical user interface (abbreviated GUI, which is pronounced “gooey”) is an interface with graphical elements such as windows, buttons, scroll bars, input fields, and other fancy doo-dads. These are distinguished from command line interfaces, which lack these elements and are text based.

hashable

Dictionary keys must be hashable. Internally, Python produces a hash (a number) corresponding to each key in a dictionary and uses this to look up elements in the dictionary. In order for this to work, such hashes must be stable—they may not change. Accordingly, Python disallows the use of non-hashable objects as dictionary keys. This includes mutable objects (lists, dictionaries) or immutable containers of mutable objects (for example, a tuple containing a list). Most other objects are hashable: integers, floats, strings, etc.

heterogeneous

Heterogeneous means “of mixed kind or type”. Python allows for heterogeneous lists or tuples, meaning that these can contain objects of different types. For example, this is just fine in Python: ['a', 42, False, [x], 101.9].

identifier

An identifier is a name we give to an object in Python. For many types, we give a name by assignment. Example:

x = 1234567

gives the value 1234567 the name (identifier) x. This allows us to refer to the value 1234567 in our code by its identifier, x.

print(x)
z = x // 100
# etc

We give identifiers to functions using the def keyword.

def successor(n):
    return n + 1

Now this function has the identifier (name) successor.

For restrictions on identifiers, see the Python documentation at https://docs.python.org/3/reference/lexical_analysis.html (section 2.3. Identifiers and keywords).

immutable

If an object is immutable it means that the object cannot be changed. In Python, int, float, str, and tuple are all immutable types. It is true that we can reassign a new value to a variable, but this is different from changing the value itself.

import

We import a module for use in our own code by using Python’s import keyword. For example, if we wish to use the math module, we must first import it thus:

import math

impure functions

Impure functions are functions with side effects. Side effects include reading from or writing to the console, reading from or writing to a file, or mutating (changing) a non-local variable. See: pure function.

incremental development

Incremental development is a process whereby we write, and presumably test, our programs in small increments.

index / indices

All sequences have indices (the plural of index). To each element in the sequence, there corresponds an index. We can use an index to access an individual element within a sequence. For this we use square bracket notation (which is distinct from the syntax used to create a list). For example, given the list

>>> lst = ['dog', 'cat', 'gerbil']

we can access individual elements by their index. Python is (like the majority of programming languages) zero-indexed so indices start at zero.

>>> lst[0]
'dog'
>>> lst[2]
'gerbil'
>>> lst[1]
'cat'

Lists, being mutable, support indexed writes as well as indexed reads, so this works:

>>> lst[2] = 'hamster'

But this won’t work with tuples or strings (since they are immutable).

I/O

I/O is short for input/output. This may refer to console I/O, file I/O, or some other form of input and output.

instance / instantiate

An instance is an object of a given type once created. For example, 1 is an instance of an object of type int. More often, though, we speak of instances as objects returned by a constructor. For example, when using the csv module, we can instantiate CSV reader and writer objects by calling the corresponding constructors, csv.reader() and csv.writer(). What are returned by these constructors are instances of the corresponding type.

integrated development environment (IDE)

Integrated development environments are convenient (but not essential) tools for writing code. Rather than a mere text editor, they provide syntax highlighting, hints, and other facilities for writing, testing, debugging, and running code. Python provides its own IDE, called IDLE (integrated development and learning environment) and there are many commercial or open source IDEs: Thonny (worth a look if you’re a beginner), JetBrains Fleet, JetBrains PyCharm, Microsoft VS Code, and many others.

interactive mode

Interactive mode is what we’re using when we’re interacting at the Python shell. At the shell, you’ll see the Python prompt >>>. Work at the shell is not saved—so it’s suitable for experimenting but not for writing programs. See: script mode, below.

interpolation

In this text, when we mention interpolation, we’re always talking about string interpolation (and not numeric interpolation or frame interpolation). See: string interpolation.

interpreter

An interpreter is a program that executes some form of code without it first being compiled into binary machine code. In Python, this is done by the Python interpreter, which interprets bytecode produced by the Python compiler.

invoke (see: call)

Invoke is synonymous with call.

iterable / iterate

An iterable object is one we may iterate, that is, it is an object which contains zero or more elements, which are ordered and can be taken one at a time. A familiar form of iteration is dealing from a deck of cards. The deck contains zero or more elements (52 for a standard deck). The deck is ordered—which doesn’t mean the cards are sorted, it just means that each card has a unique position within the deck (depending on how the deck is shuffled). If we were to turn over the cards from the top of the deck one at a time, until there were no more cards left, we’d have iterated over the deck. At the first iteration, we might turn over the six of clubs. At the second iteration, we might turn over the nine of diamonds. And so on. That’s iterating an iterable.

Iterables in Python include objects of type str, list, tuple, dict, range, and enumerate (there are others as well). When we iterate these objects, we get one element at a time, in the order they appear within the object.1 When we iterate in a loop, unless there are specific exit conditions (for example, return or break) iteration continues until the iterable is exhausted (there are no more elements remaining to iterate). Going back to the example of our deck of cards, once we’ve turned over the 52nd card, we’ve exhausted the deck, there’s nothing left to turn over, and iteration ceases.

keyword

Certain identifiers are reserved by the syntax of any language as keywords. Keywords always have the same meaning and cannot be changed by the user. Python keywords we’ve seen in this text are: False, None, True, as, assert, break, def, del, elif, else, except, for, if, import, in, not, or, pass, return, try, while, and with. Feel free to try redefining any of these at the Python shell—you won’t succeed.

keyword argument

A keyword argument is an argument provided to a function which is preceded by the name. (Note: keyword arguments have absolutely nothing to do with Python keywords.) Keyword arguments are specified in the function definition. Defining functions with keyword arguments is not covered in this text, but there are a few instances of using keyword arguments, notably:

  1. The optional end keyword argument to the print() function, which allows the user to override the default ending of printed strings (which is the newline character, \n).

  2. The optional newline keyword argument to the open() function (which is a little hack to prevent ugly behavior on certain Windows machines).

Keyword arguments, if any, always follow positional arguments.

lexicographic order

Lexicographic order is how Python orders strings and certain other type by default when sorting. This is, essentially, how strings would appear if in a conventional dictionary. For example, when sorting two words, the first letters are compared. If the first letters are different, then the word which contains the first letter which appears earlier in the alphabet appears before the other in the sort. If the first letters are the same, then the second letters are compared, and so on. If the number of letters is different, but all letters that can be compared are the same, then the shorter word appears before the other in the sort. So, for example the word 'sort' would appear before the word 'sorted' in a sorted list of words.

list

A list (type list) is a mutable container for other objects. Lists are sequences, meaning that their contents are ordered (each object in the list has a specific position within the list). Lists are iterable, meaning that we can iterate over them in a for loop. We can create a list by assigning a list literal to a variable:

cheeses = ['gouda', 'brie', 'mozzarella', 'cheddar']

or we may create a list from some other iterable object using the list constructor:

# This creates the list ['a', 'b', 'c']
letters = list(('a', 'b', 'c')) 
# This creates the list ['w', 'o', 'r', 'd']
letters = list('word')

The list constructor can also be used to make a copy of a list.

literal

A literal is an actual value of a given type. 1 is a literal of the int type. 'muffin' is a literal of the str type. ['foo', 'bar', 123] is a literal of the list type. During evaluation, literals evaluate to themselves.

local variable

A local variable is one which is defined within a limited scope. The local variables we’ve seen in this text are those created by assignment within a function.

loop

A loop is a structure which is repeated zero or more times, depending on the condition if it’s a while loop, or depending on the iterable being iterated if it’s a for loop. break and (in some cases) return can be used to exit a loop which might otherwise continue.

Python supports two kinds of loops: while loops which continue to execute as long as some condition is true, and for loops which iterate some iterable.

Matplotlib

Matplotlib is a widely used library for creating plots, animations, and other visualizations of data in Python. It is not part of the Python standard library, and so it must be installed before it can be used.

For more, see: https://matplotlib.org.

method

A method is a function which is bound to objects of a specific type.2 For example, we have list methods such as .append(), .pop(), and .sort(), string methods such as .upper(), .capitalize(), and .strip(), and so on. Methods are accessed by use of the dot operator (as indicated in the identifiers above). So to sort a list, lst, we use lst.sort(); to remove and return the last element from a non-empty list, lst, we use lst.pop(); to return a capitalized copy of a string, s, we use s.capitalize(); and so on.

module

A module is a collection of Python objects and code. Examples include the math module, the csv module, and the statistics module. In order to use a module, it must be imported, for example, import math. Imported modules are given namespaces, and we access functions within a module using the dot operator. For example, when importing the math module, the namespace is math and we access a function within that namespace thus: math.sqrt(2), as one example.

You can import programs you write yourself if you wish to reuse functions written in another program. In cases like this, your program can be imported as a module.

modulus

When using the modulo operator, we refer to the second operand as the modulus. For example, in the case of 23 % 5 the modulus is 5.

See also: Euclidean division and congruent.

Monte Carlo

Monte Carlo method makes use of repeated random sampling (from some distribution), in order to solve certain classes of problems. For example, we can use the Monte Carlo method to approximate \pi. The Monte Carlo method is widely used in physics, economics, operations management, and many other domains.

mutable

An object (type) is mutable if it can be changed after it’s been created. Lists and dictionaries are mutable, whereas objects of type int, float, str and tuple are not.

name (see: identifier)

Name is synonymous with identifier.

namespace

Namespaces are places where Python objects are stored, and these are very much like but not identical to dictionaries. For example, like dictionary keys, identifiers within a namespace are unique (you can’t have two different variables named x in the same namespace).

Most often you’re working in the global namespace. However, functions, and modules you import have their own namespaces. In the case of functions, a function’s namespace is created when the function is called, and destroyed when the function returns. In the case of modules, we refer to elements within a module’s namespace using the dot operator (see: Module).

node (graph; see: vertex)

In the context of graphs, node and vertex are synonymous.

object

Pretty much anything in Python that’s not a keyword or operator or punctuation is an object. Every object has a type, so we have objects of type int, objects of type str, and so on. Functions are objects of type function.

If you learn about object-oriented programming you’ll learn how to define your own types, and instantiate objects of those types.

operator

An operator is a special symbol (or combination of symbols) that takes one or more operands and performs some operation such as addition, multiplication, etc., or some kind of comparison. Operators include (but are not limited to) +, -, *, **, /, //, %, =, ==, > <, >=, <=, and !=. Operators that have a single operand are called unary operators, for example, unary negation. Operators that take two operands are called binary operators.

Some operators perform different operations depending on the type of their operands. This is called operator overloading. Example: If both operands are numeric, + performs addition; if both operands are strings, or both operands are lists, + performs concatenation.

parameter (and formal parameter)

A function definition may include one or more parameter (also called formal parameter). These parameters provide names for arguments when the function is called. For example:

def square(x):
    return x * x

In this example, x is the formal parameter, and in order to call the function we must supply a corresponding argument.

y = square(12)
y = square(some_variable)

The examples above show function calls supplying arguments which are assigned to the formal parameter in the function definition.

Formal parameters exist only within a functions namespace (which is destroyed upon return). See: namespace.

PEP 8

PEP 8 is the official Python style guide. See: https://peps.python.org/pep-0008/

pseudo-random

It is impossible for a computer to produce a truly random number (whatever that might actually be). Instead, they can produce pseudo-random numbers which appear random and approximate certain distributions. Pseudo-random number generation is implemented in Python’s random module. See: Chapter 12 Randomness, games, and simulations, for more.

pure function

A pure function is a function without side effects. Furthermore, the output of a pure function (the value returned), depends solely on the argument(s) supplied and the function definition, and given the same argument a pure function will always return precisely the same result. In this regard, pure functions are akin to mathematical functions. See: impure function.

quantile

In statistics, a quantile is a set of points which divide a distribution or data set into intervals of equal probability. For example, if we divide our data into quartiles (a quantile of four parts), then each of the four parts has equal probability. Note that if dividing into n parts we need n - 1 values to do so.

Some quantiles have special names. For example, we call the value that divides a distribution, sample or population into two equally probable parts a median. If we divide into 100 parts we call that percentiles.

quotient

A quotient is the result of division, whether floor division or floating-point division. In the case of / and //, the value yielded is called the quotient.

random walk

A random walk is a mathematical object which describes a path in some space (say, the integers) taken by a repeated random sequence of steps. For example, if the space in question is the integers, if we start at zero, we could take a random walk by repeatedly flipping a fair coin and adding one if the toss comes up heads and subtracting one if the toss comes up tails.

A random walk needn’t be constrained to a single dimension. For example, we could model the motion of a particle suspended in a fluid (Brownian motion) by a random walk in three-dimensional space.

Random walks are used in modeling many phenomena in engineering, physics, chemistry, ecology, economics, and other domains.

read-evaluate-print loop (REPL)

A read-evaluate-print loop is an interactive interface which allows a user to type commands or expressions at a prompt, have them performed or evaluated, and then see the result printed to the console. This is performed in a loop, allowing the user to continue indefinitely until they choose to terminate the session. The Python shell is an example.

remainder

The remainder is the quantity left over after performing Euclidean (floor) division. The remainder of such an operation must be in the interval [0, m) where m is the divisor (or modulus). Notice that this is a half-open interval. For example if we divide 31 by 6, the remainder is 1. This is implemented in Python with the modulo operator, %. See also: modulo, and relevant sections in Chapter 4.

replacement field

Within an f-string, a replacement field indicates where expressions are to be interpolated within the string. Replacement fields are delimited by curly braces. Example: f"Hello {name}, it's nice to meet you!"

representation error

Representation error of floating-point numbers is the inevitable result of the fact that the real numbers are infinite and the representation of numbers in a computer is finite—there are infinitely more real numbers than can be represented on a computer using a finite number of bits.

return value

All Python functions return a value, and we call this the return value. For example, math.sqrt() returns the square root of the argument supplied (with some restrictions). As noted, all Python functions return a value, though in some cases the value returned is None. Functions which return None include (but are not limited to) print() and certain list methods which modify a list in place (for example, .append(), .sort()).

rubberducking

Rubberducking is a process whereby a programmer tries to explain their code to a rubber duck, and in so doing (hopefully) solves a problem or realizes what needs to be done in order to fix a bug. Rubber ducks are particularly useful in this respect in that they listen without interruption, and, not being too bright, they require the simplest possible explanation from the programmer. If you get stuck, talk to the duck!

run time

Run time (or sometimes runtime) refers to the time at which a program is run.

scope

Scope refers to the visibility or lifetime of a name (or identifier). For example, variables first defined in assignment statements within a function or formal parameters of a function are local to that function, and when the function returns and its namespace is destroyed such local variables are out of scope.

We often refer to inner scope as the scope within the body of a function or method, and outer scope to the code outside the body of a function.

See also: Chapter 5 Functions, and glossary entry for namespace.

script mode

Script mode refers to the mode of operation at work when we run a program that we’d previously written and saved. This is distinct from interactive mode which takes place in the Python shell.

seed

A seed is a starting point for calculations used to generate a pseudo-random number (or sequence of pseudo-random numbers). Usually, when using functions from the random module, we allow the random number generator to use the seed provided by the computer’s operating system (which is designed to be as unpredictable as possible). Sometimes, however, and especially in cases where we wish to test code which includes the use of pseudo-random numbers, we explicitly set the seed to a known value. In doing so, we can reproduce the sequence of pseudo-random numbers. See: Chapter 12 Randomness, games, and simulations.

semantics

Semantics refers to the meaning of our code as distinct from the syntax required by the language. Bugs are defects of semantics—our code doesn’t mean (or do) what we intend it to mean (or do).

sequence unpacking

Sequence unpacking is a language feature which allows us to unpack values within a sequence to individual variables. Examples:

>>> lst = [1, 2, 3]
>>> a, b, c = lst
>>> a
1
>>> b
2
>>> c
3
>>> coordinates = (44.47844, -73.19758)
>>> lat, lon = coordinates
>>> lat
44.47844
>>> lon
-73.19758

In order for sequence unpacking to work, there must be exactly the same number of variables on the left-hand side of the assignment operator as there are elements to unpack in the sequence on the right-hand side. Accordingly, sequence unpacking is not useful (or perhaps impossible) if there are a large number of elements to be unpacked or the number of elements is not known. This is why we see examples of tuple unpacking more than we do of list unpacking (since lists are mutable, we can’t always know how many elements they contain).

Tuple unpacking is the preferred idiom in Python when working with enumerate(). It is also handy for swapping variables.

shadowing

Shadowing occurs when we use the same identifier in two different scopes, with the name in the inner scope shadowing the name in the outer scope. In the case of functions, which have their own namespace, shadowing is permitted (it’s syntactically legal) and Python is not confused about identifiers. However, even experienced programmers are often confused by shadowing. It not only affects the readability of the code, but it can also lead to subtle defects that can be hard to pin down and fix. Accordingly, shadowing is discouraged (this is noted in PEP 8).

Here’s an example:

def square(x):
    x = x * x
    return x
    
if __name__ == '__main__':
    x = float(input("Enter a number and I'll square it: "))
    print(square(x)

One confusion I’ve seen among students arises from using the same name x. For example, thinking that because x is assigned the result of x * x in the body of the function, that the return value is unnecessary:

def square(x):
    x = x * x
    return x
    
if __name__ == '__main__':
    x = float(input("Enter a number and I'll square it: "))
    square(x)
    print(x)  # this prints the x here from the outer scope!

The first example, above, is correct (despite shadowing) and the program prints the square of the number entered by the user. In the second example, however, the program does not print the square of the number entered by the user—instead it prints the number that was originally entered by the user.3

side effect

A side effect is an observable behavior of a function other than simply returning a result. Examples of side effects include printing or prompting the user for information, or mutating a mutable object that’s been passed to the function (which affects the object in the outer scope).

Whenever writing a function, any side effects should be included by design and never inadvertently. Hence, pure functions are preferred to impure functions wherever possible.

slice / slicing

Python provides a convenient notation for extracting a subset from a sequence. This is called slicing. For example, we can extract every other letter from a string:

>>> s = 'omphaloskepsis'
>>> s[::2]
'opaokpi'

We can extract the first five letters, or the last three letters:

>>> s[:5]
'ompha'
>>> s[-3:]
'sis'

We call the result of such operations slices. In general, the syntax is s[<start>:<stop>:<stride>], where s is some sequence. As indicated in the above examples, stride is optional.

See: Chapter 10 Sequences for more.

snake case

Snake case is a naming convention in which all letters are lower case, and words are separated by underscores (keeping everything down low, like a snake slithering on the ground). Your variable names and function names should be all lower case or snake case. Sometimes stylized as snake_case.

See: PEP 8.

standard deviation

Standard deviation is a measure of variability in a distribution, sample or population. Standard deviation is calculated with respect to the mean.

See: Chapter 14 Data analysis and presentation, for details on how standard deviation is calculated.

statement

`A statement is either an expression or one of several constructs with a keyword, such asif,whileorfor''.\footnote{Source: Python Language Reference}\index{statement} Examples include assignment statements, branching statements, loop control statements, andwithstatements. A statement may, however, contain an expression, for exampleif x > 0:ory = 2 * x + 3`.

For example, consider a simple assignment statement:

>>> x = 1
>>>

Notice that nothing is printed to the console after making the assignment. This is because x = 1 is a statement and not an expression. Expressions have evaluations, but statements do not.

Don’t confuse matters by thinking, for example, that the control statement of a while loop has an evaluation. It does not. It is true that the condition must be an expression, but the control statement itself does not have an evaluation (nor do if statements, elif statements, etc.).

static typing / statically typed

Some languages (not Python) are statically typed. In the case of static typing the type of all variables must be known at compile time and while the value of such variables may change, their types cannot. Examples of statically typed languages: C, C++, Haskell, OCaml, Java, Rust, Go, etc.

stride

Stride refers to the step size in the context of range objects and slices. In both cases, the default is 1, and thus can be excluded by the syntax. For example, both x[0:10] and range(0, 10) are syntactically valid. If, however, we wish to use a different stride, we must supply the argument explicitly, for example, x[0:10:2] and range(0, 10, 2).

string

A string is a sequence, an ordered collection of characters (or more precisely Unicode code points).

string interpolation

String interpolation is the substitution of values into a string containing some form of placeholder. Python supports more than one form of string interpolation, but most examples given in this text make use of f-strings for string interpolation. There are some use cases which justify the use of earlier, so-called C-style string interpretation, but f-strings have been the preferred method for most other use cases since their introduction in 2002 with Python 3.6.

summation

A summation (in mathematical notation, with \sum) is merely the addition of all terms in some collection (list, tuple, etc.). Sometimes, a summation is nothing more than adding a bunch of numbers. In such cases, Python’s built-in sum() suffices. In other cases, it is the result of some calculation which must be summed, say, for example, summing the squares of all numbers in some collection. In cases like this, we implement the summation in a loop.

syntax

The syntax of a programming language is the collection of all rules which determine what is permitted as valid code. If your code contains syntax errors, a SyntaxError (or subclass thereof) is raised.

terminal

Most modern operating systems provide a terminal (or more strictly speaking a terminal emulator) which provides a text-based command line interface for issuing commands.

The details of how to open a terminal window will vary depending on your operating system.

top-level code environment

The top-level code environment is where top-level code is executed. We specify the top-level code environment (perhaps unwittingly) when we run a Python program (either from the terminal or within an IDE). We distinguish the top-level environment from other modules which we may import as needed to run our code.

See: entry point, and Chapter 9 Structure, development, and testing.

truth value

Almost everything (apart from keywords) in Python has a truth value even if it is not strictly a Boolean or something that evaluates to a Boolean. This means that programmers have considerable flexibility in choosing conditions for flow of control (branching and loop control).

For example, we might want to perform operations on some list, but only if the list is non-empty. Python obliges by treating a non-empty as having a “true” truth value (we say it’s truthy) and by treating an empty list as something “false” or “falsey.” Accordingly, we can write:

if lst:
    # Now we know the list is not empty and we can
    # do whatever it is we wish to do with the 
    # elements of the list.

See: Chapter 8 Branching and Boolean expressions, especially sections covering truthy and falsey.

truthy

In Python, many things are treated as if they evaluated to True when used as conditions in while loops or branching statements. We call such things truthy. This includes numerics with non-zero values, and any non-empty sequence, and many other objects.

tuple

A tuple is an immutable sequence of objects. They are similar to lists in that they can contain heterogeneous elements (or none at all), but they differ from lists in that they cannot be changed once created.

See: Chapter 10 Sequences for details.

type

Python allows for many different kinds of object. We refer to these kinds as types. We have integers (int), floating-point numbers (float), strings (str), lists (list), tuples (tuple), dictionaries (dict), functions (function), and many other types. An object’s type determines not just how it is represented internally in the computer’s memory, but also what kinds of operations can be performed on objects of various types. For example, we can divide one number by another (provided the divisor isn’t zero) but we cannot divide a string by a number or by another string.

type inference

Python has limited type inference, called “duck typing” (which means if it looks like a duck, and quacks like a duck, chances are pretty good it’s a duck). So when we write

x = 17

Python knows that the identifier x has been assigned to an object of type int (we don’t need to supply a type annotation as is required in, say, C or Java).

However, as noted in the text, Python doesn’t care a whit about the types of formal parameters or return values of functions. Some languages can infer these types as well, and thus can ensure that programmers can’t write code that calls a function with arguments of the wrong type, or returns the wrong type from a function.

Unicode

Unicode is a widely-used standard for encoding symbols (letters, glyphs, and others). Python has provided full Unicode support since version 3.0, which was released in 2008. For purposes of this textbook, it should suffice that you understand that Python strings can contain letters, letters with diacritic marks (accents, umlauts, etc.), letters from different alphabets (from Cyrillic to Arabic to Thai), symbols from non-alphabetic writing systems (Chinese, Japanese, hieroglyphs, Cuneiform, Cherokee, Igbo), mathematical symbols, and a tremendous variety of bullets, arrows, icons, dingbats—even emojis!

unpacking

See: sequence unpacking.

variable

Answering the question, What is a variable? can get a little thorny. I think it’s most useful to think of a variable as a name bound to a value forming a pair—two things, tightly connected.

Take the result of this assignment

animal = 'porcupine'

Is the variable just the name, animal? No. Is the variable just the value, 'porcupine'? No. It really is these two things together: a name attached to a value.

Accordingly, we can speak of a variable as having a name and a value.

What’s the name of this variable? animal.

What’s the value of this variable? 'porcupine'.

We sometimes speak of the type of a variable, and while names do not have types in Python, values do.

vertex (graph)

As noted elsewhere, a graph consists of a set of vertices (the plural of vertex), and a set of edges (which connect vertices).

If we were to represent a highway map with a graph, the cities and towns would be represented by vertices, and the highways connecting them would be the edges of the graph.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. Dictionaries are a bit of a special case here, since the order in which elements are added to a dictionary is not necessarily the order in which they appear when iterating, but there is an underlying order. Moreover, Python does provide an OrderedDict type (provided by the collections module) which preserves the order of addition when iterating. But these are minor points.↩︎

  2. Strictly speaking, a method is a function defined with a class.↩︎

  3. Yeah, OK, if the user enters 0 or 1, the program will print the square of the number, but as they say, even a broken clock tells the right time twice a day! That’s not much consolation, though when the user enters 3 and expects 9 as a result.↩︎