Text stringlengths 1 9.41k |
|---|
Note that if dividing into 𝑛 parts we need 𝑛−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 floatingpoint 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
co... |
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-pr... |
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, 𝑚) where 𝑚 is the divisor (or modulus). Notice that this is a halfopen 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... |
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) ... |
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 ex-_
ample, 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
o... |
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 pseudorandom 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 syn-_
_tax 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 val-_
ues 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 ... |
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) ... |
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 n... |
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 t... |
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'
```
3Yeah, OK, if the user enters 0 or 1, the program will print the square of the
... |
That’s
not much consolation, though when the user enters 3 and expects 9 as a result.
-----
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 Languag... |
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 syntacticall... |
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... |
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 ∑) is merely the addition
of all term... |
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 wil... |
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 someth... |
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 l... |
We call such
things truthy. This includes numerics with non-zero values, and any nonempty 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... |
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 func... |
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,... |
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... |
For example, 4 ∈{4, 12, 31}.
∉ is used to indicate that some object is not an element of some set.
For example, 7 ∉{4, 12, 31}.
ℕ denotes the set of all natural numbers, that is, 0, 1, 2, 3, …
ℤ denotes the set of all integers, that is, … −2, −1, 0, 1, 2, …
ℝ denotes the set of all real numbers. |
Unlike the integers, real numbers
can be used to measure continuous quantities.
Sometimes we describe a set by stating the properties that must hold
for its members. |
In such cases, we use the vertical bar, |, which can be
read “such that.” For example, {𝑥∈ℝ| 𝑥≥0} is the set of all real
numbers greater than or equal to zero.
ℚ is the set of all rational numbers, that is, ℚ= { [𝑎]𝑏 [| 𝑎, 𝑏∈ℤ, 𝑏≠0}][.]
≡ denotes congruence. |
We write 𝑎≡𝑏(mod 𝑚) to indicate that 𝑎 is
congruent to 𝑏 {modulo} 𝑚. For example, 5 ≡1 (mod 2), and 72 ≡18
(mod 9).
∘ is the composition operator. |
For example, 𝑓∘𝑔 is the composition of
functions 𝑓 and 𝑔. |
With this notation, composition is performed rightto-left, so it may be helpful to read 𝑓∘𝑔 as “f applied after g.”
Square brackets denote closed intervals, the elements of the interval
usually determined by context. |
For example, [0, 12] = {𝑛∈ℤ| 0 ≤𝑛≤
12} and [𝜋, 2𝜋] = {𝑥∈ℝ| 𝜋≤𝑥≤2𝜋}.
Parentheses denote open intervals—those in which the endpoints are
not included. |
For example, (0, 12) = {𝑛∈ℤ| 0 < 𝑛< 12} and (𝜋, 2𝜋) =
{𝑥∈ℝ| 𝜋< 𝑥< 2𝜋} (note the strict inequalities).
_Half-open intervals are denoted with a square bracket on one side and_
a parenthesis on the other. |
For example, [0, 12) = {𝑛∈ℤ| 0 ≤𝑛< 12}
and (𝜋, 2𝜋] = {𝑥∈ℝ| 𝜋< 𝑥≤2𝜋}.
359
-----
_Subscripts are used to denote individual elements within a set or se-_
quence. |
For example, 𝑥𝑖 is the 𝑖th element of the sequence 𝑋, and we
call 𝑖 the index of the element. Note: In this text, indices start with 0.
Σ denotes a summation. |
For example, given the set 𝑋= {2, 9, 3, 5, 1},
Σ 𝑥𝑖 is the sum of all elements of 𝑋, that is 2 + 9 + 3 + 5 + 1 = 20.
Sometimes, an operation or operations are applied to the elements of a
summation. |
For example, given the set 𝑋= {1, 2, 3}, Σ 𝑥[2]𝑖 [is the sum of]
the squares of all elements of 𝑋, that is 1[2] + 2[2] + 3[2] = 1 + 4 + 9 = 14.
Π (upper-case) denotes a repeated product. |
For example, given the
set 𝑋= {2, 9, 3, 5, 1}, Π 𝑥𝑖 is the product of all elements of 𝑋, that is
2 × 9 × 3 × 5 × 1 = 270.
𝜋 (lower-case) is a mathematical constant, the ratio of a circle’s circumference to its diameter. |
This is approximately equal to
3.141592653589793.
In statistics, 𝜇 is used to denote the mean of a sample, population,
or distribution. You may have seen ̄𝑥 in other texts. |
These are different
notations for the same thing.
In statistics, 𝜎 denotes the standard deviation of a sample, population,
or distribution (𝜎[2] denotes the variance).
√
± denotes “plus or minus” for example, 𝜇± 2.5𝜎 or −𝑏± 𝑏[2] −4𝑎𝑐.
-----
#### Appendix C
```
pip and venv
###### Introduction
```
This cove... |
If you are using an IDE other than IDLE,
chances are that your IDE has an interface for managing packages and
virtual environments. |
The instructions that follow are intended more for
people who are not using an IDE other than IDLE, or who are the DIY
type, or simply those who are more interested in how Python and the
Python ecosystem work. |
What follows is for users of Python version 3.4
or later.
###### PyPI, pip, and venv
There is a huge repository of modules you can use in your own projects.
This repository is called PyPI—the Python Package Index—and it’s
[hosted at https://pypi.org/.](https://pypi.org/)
The Python Package Index (PyPI) is a reposito... |
There are almost half a million projects hosted on PyPI. It’s
often the case that we want to install packages hosted on PyPI, which
do not ship with Python. |
Fortunately, there are tools that make this less
challenging than it might be otherwise. Two of the most useful of these
are pip and venv.
```
pip is the package installer for Python. |
You can use this to install
```
any packages listed on PyPI. pip will manage all dependencies for you.
What are dependencies? |
It’s often the case that one package on PyPI requires another (sometimes dozens), and each of those might require other
packages. pip takes care of all that for you. |
pip identifies all packages
361
-----
that might be needed for the package you request and will automatically
download and install them, usually with a single command.
The other tool presented here is venv. |
This is, perhaps, a little more
abstract and can often confuse beginners, but in most cases it’s not
too complicated. |
What venv does is create a virtual environment where
you can install packages using pip. First, we’ll walk through the reasons
behind virtual environments and how to create one using venv. |
Then
we’ll see how to activate that virtual environment, install packages using
```
pip, and start coding.
```
[Of course, you can follow the directions at https://packaging.pyth](https://packaging.python.org/en/latest/tutorials/installing-packages/#creating-and-using-virtual-environments)
[on.org/en/latest/tutorials/... |
Because of this, we don’t usually want
to monkey with the OS-installed Python environment (in fact, doing so
can break certain components of your OS). |
So installing packages to your
OS-installed (or otherwise protected) Python environment is usually a
bad idea. This is where virtual environments come in. |
With venv you
can create an isolated Python environment for your own programming
projects within which you can change Python versions, install and delete
packages, etc., without ever touching your OS-installed Python environ_ment._
Another reason you might want to use venv is to isolate and control dependencies on a pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.