Text
stringlengths
1
9.41k
For example: 327 ----- ``` 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 10 ∑(−1)[𝑖] 𝑥𝑖. 𝑖=0 Alternating sums appear quite often ...
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, 𝜇= [1] 𝑁 𝑁−1 ∑ 𝑥𝑖. 𝑖= 0 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: 2, 4, 6, 8, 10, … 7, 10, 13, 16, 19, 22, … 44, 43, 42, 41, 40, 39, … 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 ...
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 Tr...
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 ...
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 hu-_ mans) 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 ...
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 d...
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 coupli...
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 t...
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 1...
In mathematical notation, we indicate congruence with the ≡ symbol, and we can write this example as 5 ≡19 (mod 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...
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 whic...
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 divid...
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 it...
""" 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 dun_ders, 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 seque...
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 Euclid_ian 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 excep...
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!"...
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 eval...
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.