Text
stringlengths
1
9.41k
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 ⌊𝑥⌋ and, for example ⌊6.125⌋= 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 replaceme...
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 in-_ terpolation, where values are substituted into replacement fields within the f-string (with optional formatting specifiers).
The syntax for an fstring 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 rep ``` resentation 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, but...
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 heteroge-_ neous 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 th...
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 read-_ ing 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...
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 en...
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 usin...
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 order...
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 1Dictionaries 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 th...
Moreover, Python does provide an Or ----- 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 lef...
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 wh...
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. ``` deredDict type (provided by the collections module) which preserves the order of ``` addition when iterating.
But these are minor points. ----- ###### 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 ['...
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, ...
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.](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(), ...
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 𝜋.
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: ide...
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 suc...
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 t...
See: namespace. ###### PEP 8 [PEP 8 is the official Python style guide.
See: https://peps.python.org/](https://peps.python.org/pep-0008/) [pep-0008/](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.