This commit is contained in:
Hykilpikonna
2021-12-07 22:28:01 -05:00
commit 6fffdf686a
151 changed files with 37985 additions and 0 deletions
+197
View File
@@ -0,0 +1,197 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>1.1 The Different Types of Data</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<link rel="stylesheet" href="../tufte.css" />
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<div style="display:none">
\(
\newcommand{\NOT}{\neg}
\newcommand{\AND}{\wedge}
\newcommand{\OR}{\vee}
\newcommand{\XOR}{\oplus}
\newcommand{\IMP}{\Rightarrow}
\newcommand{\IFF}{\Leftrightarrow}
\newcommand{\TRUE}{\text{True}\xspace}
\newcommand{\FALSE}{\text{False}\xspace}
\newcommand{\IN}{\,{\in}\,}
\newcommand{\NOTIN}{\,{\notin}\,}
\newcommand{\TO}{\rightarrow}
\newcommand{\DIV}{\mid}
\newcommand{\NDIV}{\nmid}
\newcommand{\MOD}[1]{\pmod{#1}}
\newcommand{\MODS}[1]{\ (\text{mod}\ #1)}
\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\C}{\mathbb C}
\newcommand{\cA}{\mathcal A}
\newcommand{\cB}{\mathcal B}
\newcommand{\cC}{\mathcal C}
\newcommand{\cD}{\mathcal D}
\newcommand{\cE}{\mathcal E}
\newcommand{\cF}{\mathcal F}
\newcommand{\cG}{\mathcal G}
\newcommand{\cH}{\mathcal H}
\newcommand{\cI}{\mathcal I}
\newcommand{\cJ}{\mathcal J}
\newcommand{\cL}{\mathcal L}
\newcommand{\cK}{\mathcal K}
\newcommand{\cN}{\mathcal N}
\newcommand{\cO}{\mathcal O}
\newcommand{\cP}{\mathcal P}
\newcommand{\cQ}{\mathcal Q}
\newcommand{\cS}{\mathcal S}
\newcommand{\cT}{\mathcal T}
\newcommand{\cV}{\mathcal V}
\newcommand{\cW}{\mathcal W}
\newcommand{\cZ}{\mathcal Z}
\newcommand{\emp}{\emptyset}
\newcommand{\bs}{\backslash}
\newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor}
\newcommand{\ceil}[1]{\left \lceil #1 \right \rceil}
\newcommand{\abs}[1]{\left | #1 \right |}
\newcommand{\xspace}{}
\newcommand{\proofheader}[1]{\underline{\textbf{#1}}}
\)
</div>
<header id="title-block-header">
<h1 class="title">1.1 The Different Types of Data</h1>
</header>
<section>
<p>Data is all around us and the amount of data stored increases every single day. In todays world, decisions must be data-driven and so it is imperative that we be able to process, analyze, and understand the data we collect. Other important factors include the security and privacy of data. Businesses and governments need to answer important questions such as “Where should this data be stored?”; “How should this data be stored?”; and even, “Should this data be stored at all?”. The answers to these questions for Health Canada and personal health data is very different from the answers Nintendo might come up with for the next Animal Crossing game.</p>
<p>We begin our study of computer science by developing definitions for different categories of data. A <strong>data type</strong> is a way of categorizing data. A description of a data type conveys two important pieces of information:</p>
<ol type="1">
<li>The allowed <em>values</em> for a piece of data.</li>
<li>The allowed <em>operations</em> we can perform on a piece of data.</li>
</ol>
<p>For example, we could say that a persons age is a natural number, which would tell us that values like 25 and 100 would be expected, while an age of -2 or “David” would be nonsensical. Knowing that a persons age is a natural number also tells us what operations we could perform (e.g., “add 1 to the age”), and rules out other operations (e.g., “sort these ages alphabetically”).</p>
<p>In this section, well review the common data types that well make great use of in this course: numeric data, boolean data, textual data, and various forms of collections of data. Many terms and definitions may be review from your past studies, but be careful—they may differ slightly from what youve learned before, and it will be important to get these definitions exactly right.</p>
<h2 id="numeric-data">Numeric data</h2>
<p>Here are some types of numeric data, represented as familiar sets of numbers.</p>
<ul>
<li>A <strong>natural number</strong> is a value from the set <span class="math inline">\(\{0, 1, 2, \dots \}\)</span>. We use the symbol <span class="math inline">\(\N\)</span> to denote the set of natural numbers.<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote"> Note that our convention in computer science is to consider 0 a natural number!</span></li>
<li>An <strong>integer</strong> is a value from the set <span class="math inline">\(\{\dots, -2, -1, 0, 1, 2, \dots \}.\)</span> We use the symbol <span class="math inline">\(\Z\)</span> to denote the set of integers.</li>
<li>A <strong>rational number</strong> is a value from the set <span class="math inline">\(\{\frac{p}{q} \mid p, q \in \Z \text{ and } q \neq 0\}\)</span>—that is, the set of possible fractions. We use the symbol <span class="math inline">\(\Q\)</span> to denote the set of rational numbers.</li>
<li>An <strong>irrational number</strong> is a number with a infinite and non-repeating decimal expansion. Examples are <span class="math inline">\(\pi\)</span>, <span class="math inline">\(e\)</span>, and <span class="math inline">\(\sqrt 2\)</span>. We use the symbol <span class="math inline">\(\overline{\Q}\)</span> to denote the set of irrational numbers.</li>
<li>A <strong>real number</strong> is either a rational or irrational number. We use the symbol <span class="math inline">\(\R\)</span> to denote the set of real numbers.</li>
</ul>
<h3 id="operations-on-numeric-data">Operations on numeric data</h3>
<p>All numeric data types support the standard arithmetic operations (addition, subtraction, multiplication, division, and exponentiation), as well as the standard comparisons for equality (using <span class="math inline">\(=\)</span>) and inequality (<span class="math inline">\(&lt;\)</span>, <span class="math inline">\(\leq\)</span>, <span class="math inline">\(&gt;\)</span>, <span class="math inline">\(\geq\)</span>). And of course, you are familiar with many more numeric functions, like log and sin; these will come up throughout the course.</p>
<p>One additional arithmetic operation that may be less familiar to you is the <em>modulo operator</em>, which produces the remainder when one integer is divided by another. Well use the percent symbol <span class="math inline">\(\%\)</span> to denote the modulo operator, writing <span class="math inline">\(a \% b\)</span> to mean “the remainder when <span class="math inline">\(a\)</span> is divided by <span class="math inline">\(b\)</span>”. For example, <span class="math inline">\(10 \% 4 = 2\)</span> and <span class="math inline">\(30 \% 3 = 0\)</span>.</p>
<p>Some arithmetic operations are undefined for particular numbers; for example, we cant divide by zero, and we cant take the square root of a negative number.</p>
<h2 id="boolean-data">Boolean data</h2>
<p>A <strong>boolean</strong> is a value from the set <span class="math inline">\(\{\text{True}, \text{False}\}\)</span>. Think of a boolean value as an answer to a Yes/No question, e.g. “Is this person old enough to vote?”, “Is this country land-locked?”, and “Is this service free?”.</p>
<h3 id="operations-on-boolean-data">Operations on boolean data</h3>
<p>Booleans can be combined using <em>logical operators</em>. The three most common ones are:</p>
<ul>
<li><strong>not</strong>: reverses the value of a boolean. “not True” is False, and “not False” is True.</li>
<li><strong>and</strong>: takes two boolean values and produces True when both of the values are True, and False otherwise. For example, “True and False” is False, while “True and True” is True.</li>
<li><strong>or</strong>: takes two boolean values and produces True when at least one of the values is True, and False otherwise. For example, “True or False” is True, while “False or False” is False.</li>
</ul>
<p>Next week, well discuss these logical operators in more detail and introduce a few others.</p>
<h2 id="textual-data">Textual data</h2>
<p>A <strong>string</strong> is an ordered sequence of characters, and is used to represent text. A character can be more than just an English letter (<span class="math inline">\(a\)</span>, <span class="math inline">\(b\)</span>, <span class="math inline">\(c\)</span>, etc.): number digits, punctuation marks, spaces, glyphs from non-English alphabets, and even emojis are all considered characters, and can be part of strings. Examples include a persons name, your chat log, and the script of Shakespeares <em>Romeo and Juliet</em>.</p>
<h3 id="writing-textual-data">Writing textual data</h3>
<p>We typically will surround strings with single-quotes to differentiate them from any surrounding text, e.g., David.<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote"> We can also use double-quotes (“David”) to surround a string, but in this course we will generally prefer single-quotes for a reason well discuss in Section 1.3.</span></p>
<p>A string can have zero characters; this string is called the <em>empty string</em>, and is denoted by ` or the symbol <span class="math inline">\(\epsilon\)</span>.</p>
<h3 id="operations-on-textual-data">Operations on textual data</h3>
<p>Here are some common operations on strings.<label for="sn-2" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-2" class="margin-toggle"/><span class="sidenote"> <span class="math inline">\(s\)</span>, <span class="math inline">\(s_1\)</span>, and <span class="math inline">\(s_2\)</span> are all variables representing strings.</span></p>
<ul>
<li><p><span class="math inline">\(|s|\)</span>: <strong>string length/size</strong>. Returns the the number of characters in <span class="math inline">\(s\)</span>.</p></li>
<li><p><span class="math inline">\(s_1 = s_2\)</span>: <strong>string equality</strong>. Returns whether <span class="math inline">\(s_1\)</span> and <span class="math inline">\(s_2\)</span> have the same characters, in the same order.</p></li>
<li><p><span class="math inline">\(s + t\)</span>: <strong>string concatenation</strong>. Returns a new string consisting of the characters of <span class="math inline">\(s\)</span> followed by the characters of <span class="math inline">\(t\)</span>. For example, if <span class="math inline">\(s_1\)</span> represents the string Hello and <span class="math inline">\(s_2\)</span> represents the string Goodbye, then <span class="math inline">\(s_1 + s_2\)</span> is the string HelloGoodbye.</p></li>
<li><p><span class="math inline">\(s[i]\)</span>: <strong>string indexing</strong>. Returns the <span class="math inline">\(i\)</span>-th character of <span class="math inline">\(s\)</span>, where indexing starts at 0. (So <span class="math inline">\(s[0]\)</span> returns the first character of <span class="math inline">\(s\)</span>, <span class="math inline">\(s[1]\)</span> returns the second, etc.) For example, if <span class="math inline">\(s\)</span> represents the string Hello, then <span class="math inline">\(s[0]\)</span> is H and <span class="math inline">\(s[4]\)</span> is o.</p></li>
</ul>
<h2 id="set-data-unordered-distinct-values">Set data (unordered distinct values)</h2>
<p>A <strong>set</strong> is an unordered collection of zero or more distinct values, called its <strong>elements</strong>. Examples include: the set of all people in Toronto; the set of words of the English language; and the set of all countries on Earth.</p>
<h3 id="writing-sets">Writing sets</h3>
<p>We write sets using curly braces in two different ways:</p>
<ol type="1">
<li>Writing each element of the set within the braces, separated by commas. For example, <span class="math inline">\(\{1, 2, 3\}\)</span> or <span class="math inline">\(\{\text{hi&#39;}, \text{bye&#39;}\}\)</span>.</li>
<li>Using <em>set builder notation</em>, in which we define the form of elements of a set using variables. We saw an example of this earlier when defining the set of rational numbers, <span class="math inline">\(\{\frac{p}{q} \mid p, q \in \Z \text{ and } q \neq 0\}\)</span>.</li>
</ol>
<p>A set can have zero elements; this set is called the <em>empty set</em>, and is denoted by <span class="math inline">\(\{\}\)</span> or the symbol <span class="math inline">\(\emptyset\)</span>.</p>
<h3 id="operations-on-set-data">Operations on set data</h3>
<p>Here are some common set operations.<label for="sn-3" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-3" class="margin-toggle"/><span class="sidenote"><span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span> represent sets.</span></p>
<ul>
<li><p><span class="math inline">\(|A|\)</span>: returns the <strong>size</strong> of set <span class="math inline">\(A\)</span>, i.e., the number of elements in <span class="math inline">\(A\)</span>.</p></li>
<li><p><span class="math inline">\(x \in A\)</span>: returns True when <span class="math inline">\(x\)</span> is an element of <span class="math inline">\(A\)</span>; <span class="math inline">\(y \notin A\)</span> returns True when <span class="math inline">\(y\)</span> is <em>not</em> an element of <span class="math inline">\(A\)</span>.</p></li>
<li><p><span class="math inline">\(A \subseteq B\)</span>: returns True when every element of <span class="math inline">\(A\)</span> is also in <span class="math inline">\(B\)</span>. We say in this case that <span class="math inline">\(A\)</span> is a <strong>subset</strong> of <span class="math inline">\(B\)</span>.</p>
<p>A set <span class="math inline">\(A\)</span> is a subset of itself, and the empty set is a subset of every set: <span class="math inline">\(A \subseteq A\)</span> and <span class="math inline">\(\emptyset \subseteq A\)</span> are always True.</p></li>
<li><p><span class="math inline">\(A = B\)</span>: returns True when <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span> contain the exact same elements.</p></li>
</ul>
<p>The following operations return sets:</p>
<ul>
<li><p><span class="math inline">\(A \cup B\)</span>, the <strong>union</strong> of <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span>. Returns the set consisting of all elements that occur in <span class="math inline">\(A\)</span>, in <span class="math inline">\(B\)</span>, or in both.</p>
<p>Using set builder notation: <span class="math inline">\(A \cup B = \{x \mid x \in A \text{ or } x \in B\}\)</span>.</p></li>
<li><p><span class="math inline">\(A \cap B\)</span>, the <strong>intersection</strong> of <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span>. Returns the set consisting of all elements that occur in both <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span>.</p>
<p>Using set builder notation: <span class="math inline">\(A \cap B = \{x \mid x \in A \text{ and } x \in B\}\)</span>.</p></li>
<li><p><span class="math inline">\(A \setminus B\)</span>, the <strong>difference</strong> of <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span>. Returns the set consisting of all elements that are in <span class="math inline">\(A\)</span> but that are not in <span class="math inline">\(B\)</span>.</p>
<p>Using set builder notation: <span class="math inline">\(A \setminus B = \{x \mid x \in A \text{ and } x \notin B\}.\)</span></p></li>
<li><p><span class="math inline">\(A \times B\)</span>, the <strong>(Cartesian) product</strong> of <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span>. Returns the set consisting of all <em>pairs</em> <span class="math inline">\((a, b)\)</span> where <span class="math inline">\(a\)</span> is an element of <span class="math inline">\(A\)</span> and <span class="math inline">\(b\)</span> is an element of <span class="math inline">\(B\)</span>.</p>
<p>Using set builder notation: <span class="math inline">\(A \times B = \{(x, y) \mid x \in A \text{ and } y \in B\}.\)</span></p></li>
<li><p><span class="math inline">\(\cP(A)\)</span>, the <strong>power set</strong> of <span class="math inline">\(A\)</span>, returns the set consisting of all subsets of <span class="math inline">\(A\)</span>.<label for="sn-4" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-4" class="margin-toggle"/><span class="sidenote">Food for thought: what is the relationship between <span class="math inline">\(|A|\)</span> and <span class="math inline">\(|\cP(A)|\)</span>?</span> For example, if <span class="math inline">\(A = \{1,2,3\}\)</span>, then <span class="math display">\[\cP(A) = \big\{ \emptyset, \{1\},\{2\},\{3\},\{1,2\},\{1,3\},\{2,3\},\{1,2,3\}\big\}.\]</span></p>
<p>Using set builder notation: <span class="math inline">\(\cP(A) = \{S \mid S \subseteq A\}\)</span>.</p></li>
</ul>
<h2 id="list-data-ordered-values">List data (ordered values)</h2>
<p>A <strong>list</strong> is an ordered collection of zero or more (possibly duplicated) values, called its elements. List data is used instead of a set when the elements of the collection should be in a specified order, or if it may contain duplicates. Examples include: the list of all people in Toronto, ordered by age; the list of words of the English language, ordered alphabetically, and the list of names of students at U of T (two students may have the same name!), ordered alphabetically.</p>
<h3 id="writing-lists">Writing lists</h3>
<p>Lists are written with square brackets enclosing zero or more values separated by commas. For example, <span class="math inline">\([1, 2, 3]\)</span>.</p>
<p>A list can have zero elements; this list is called the <em>empty list</em>, and is denoted by <span class="math inline">\([]\)</span>.</p>
<h3 id="operations-on-list-data">Operations on list data</h3>
<p>Here are some common list operations.<label for="sn-5" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-5" class="margin-toggle"/><span class="sidenote"><span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span> represent lists.</span></p>
<ul>
<li><p><span class="math inline">\(|A|\)</span>: returns the <strong>size</strong> of <span class="math inline">\(A\)</span>, i.e., the number of elements in <span class="math inline">\(A\)</span> (counting all duplicates).</p></li>
<li><p><span class="math inline">\(x \in A\)</span>: same meaning as for sets.</p></li>
<li><p><span class="math inline">\(A = B\)</span>: <span class="math inline">\(A\)</span> and <span class="math inline">\(B\)</span> have the same elements in the same order.</p></li>
<li><p><span class="math inline">\(A[i]\)</span>: <strong>list indexing</strong>. Returns the <span class="math inline">\(i\)</span>-th element of <span class="math inline">\(A\)</span>, where the indexing starts at 0. So <span class="math inline">\(A[0]\)</span> returns the first element of <span class="math inline">\(A\)</span>, <span class="math inline">\(A[1]\)</span> returns the second, etc.</p></li>
<li><p><span class="math inline">\(A + B\)</span>: <strong>list concatenation</strong>. Returns a new list consisting of the elements of <span class="math inline">\(A\)</span> followed by the elements of <span class="math inline">\(B\)</span>. This is similar to set union, but duplicates are kept, and order is preserved.</p>
<p>For example, <span class="math inline">\([1, 2, 3] + [2, 4, 6] = [1, 2, 3, 2, 4, 6]\)</span>.</p></li>
</ul>
<h2 id="mapping-data">Mapping data</h2>
<p>Finally, a <strong>mapping</strong> is an unordered collection of pairs of values. Each pair consists of a <em>key</em> and an associated <em>value</em>; the keys must be unique in the mapping, but the values can be duplicated. A key cannot exist in the mapping without a corresponding value.</p>
<p>Mappings are used to represent associations between two collections of data. For example: a mapping from the name of a country to its GDP; a mapping from student number to name; and a mapping from food item to price.</p>
<h3 id="writing-mappings">Writing mappings</h3>
<p>We use curly braces to represent a mapping.<label for="sn-6" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-6" class="margin-toggle"/><span class="sidenote"> This is similar to sets, because mappings are quite similar to sets. Both data types are unordered, and both have a uniqueness constraint (a sets elements are unique; a mappings keys are unique).</span> Each key-value pair in a mapping is written using a colon, with the key on the left side of the colon and its associated value on the right. For example, here is how we could write a mapping representing the menu items of a restaurant: <span class="math display">\[\{\text{`fries&#39;}: 5.99, \text{`steak&#39;}: 25.99, \text{`soup&#39;}: 8.99\}.\]</span></p>
<h3 id="operations-on-mappings">Operations on mappings</h3>
<p>Here are some common set operations.<label for="sn-7" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-7" class="margin-toggle"/><span class="sidenote"><span class="math inline">\(M\)</span> and <span class="math inline">\(N\)</span> represent mappings.</span></p>
<ul>
<li><span class="math inline">\(|M|\)</span>: returns the <strong>size</strong> of the mapping <span class="math inline">\(M\)</span>, i.e., the number of key-value pairs in <span class="math inline">\(M\)</span>.</li>
<li><span class="math inline">\(M = N\)</span>: returns whether two mappings are equal, i.e., when they contain exactly the same key-value pairs.</li>
<li><span class="math inline">\(k \in M\)</span>: returns whether <span class="math inline">\(k\)</span> is a <em>key</em> contained in the mapping <span class="math inline">\(M\)</span>.</li>
<li><span class="math inline">\(M[k]\)</span>: when <span class="math inline">\(k\)</span> is a key in <span class="math inline">\(M\)</span>, this operation returns the value that corresponds to <span class="math inline">\(k\)</span> in the mapping <span class="math inline">\(M\)</span>.</li>
</ul>
<h2 id="and-more">…and more!</h2>
<p>The data types weve studied so far are not the only kinds of data that we encounter in the real world, but they do form a basis for representing all kinds of more complex data. Well study how to represent more complex forms of data later in this course, but heres one teaser: representing image data.</p>
<p><img src="images/chelsea_channels.png" alt="Chelsea Cat Split by Colour Channel" /><br />
</p>
<p>Images can be represented as a list of integers. Each element in the list corresponds to a very tiny dot on your screen—a <em>pixel</em>. For each dot, three integer values are used to represent three colour channels: red, green, and blue. We can then add these channels together to get a very wide range of colours (this is called the RGB colour model). Somehow, our computers are able to take these sequences of integers and translate them into a sequence of visible lights and if these lights are arranged in a particular way, well, a cat appears!</p>
<h2 id="references">References</h2>
<ol type="1">
<li>Check out <a href="https://en.wikipedia.org/wiki/Our_World_in_Data">Our World in Data</a> to see how data-driven research is being used to tackle global problems.</li>
<li>If youd like to read more about the RGB colour model, the Wikipedia entry is a good start: <a href="https://en.wikipedia.org/wiki/RGB_color_model" class="uri">https://en.wikipedia.org/wiki/RGB_color_model</a>.</li>
</ol>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>1.2 Introducing the Python Programming Language</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<link rel="stylesheet" href="../tufte.css" />
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<div style="display:none">
\(
\newcommand{\NOT}{\neg}
\newcommand{\AND}{\wedge}
\newcommand{\OR}{\vee}
\newcommand{\XOR}{\oplus}
\newcommand{\IMP}{\Rightarrow}
\newcommand{\IFF}{\Leftrightarrow}
\newcommand{\TRUE}{\text{True}\xspace}
\newcommand{\FALSE}{\text{False}\xspace}
\newcommand{\IN}{\,{\in}\,}
\newcommand{\NOTIN}{\,{\notin}\,}
\newcommand{\TO}{\rightarrow}
\newcommand{\DIV}{\mid}
\newcommand{\NDIV}{\nmid}
\newcommand{\MOD}[1]{\pmod{#1}}
\newcommand{\MODS}[1]{\ (\text{mod}\ #1)}
\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\C}{\mathbb C}
\newcommand{\cA}{\mathcal A}
\newcommand{\cB}{\mathcal B}
\newcommand{\cC}{\mathcal C}
\newcommand{\cD}{\mathcal D}
\newcommand{\cE}{\mathcal E}
\newcommand{\cF}{\mathcal F}
\newcommand{\cG}{\mathcal G}
\newcommand{\cH}{\mathcal H}
\newcommand{\cI}{\mathcal I}
\newcommand{\cJ}{\mathcal J}
\newcommand{\cL}{\mathcal L}
\newcommand{\cK}{\mathcal K}
\newcommand{\cN}{\mathcal N}
\newcommand{\cO}{\mathcal O}
\newcommand{\cP}{\mathcal P}
\newcommand{\cQ}{\mathcal Q}
\newcommand{\cS}{\mathcal S}
\newcommand{\cT}{\mathcal T}
\newcommand{\cV}{\mathcal V}
\newcommand{\cW}{\mathcal W}
\newcommand{\cZ}{\mathcal Z}
\newcommand{\emp}{\emptyset}
\newcommand{\bs}{\backslash}
\newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor}
\newcommand{\ceil}[1]{\left \lceil #1 \right \rceil}
\newcommand{\abs}[1]{\left | #1 \right |}
\newcommand{\xspace}{}
\newcommand{\proofheader}[1]{\underline{\textbf{#1}}}
\)
</div>
<header id="title-block-header">
<h1 class="title">1.2 Introducing the Python Programming Language</h1>
</header>
<section>
<p>For the thousands of years of human history before the mid-twentieth century, humans collected, analysed, and created data by hand. Digital computers were a revolution not just in technology but in civilization because of their ability to store more data than could fit on all the sheets of paper in the world, and to perform computations on this data faster and more reliably than an army of humans. Today, we rely on complex computer programs to operate on data in a variety of ways, from sending messages back and forth with loved ones, organizing data in documents and media, to running simulations of physical, social, and biological systems.</p>
<p>Yet for all their computation power, computers have one fundamental limitation: they have no agency, no inherent ability to make decisions about what to do. All they can do is take a set of (possibly very complex!) instructions, what we call a <em>computer program</em>, and execute them—no more, and no less. And so if we, as computer scientists, want to harness the awesome power of computers, we need to learn how give these instructions in a way that a computer understands. We need to learn how to speak to a computer.</p>
<h2 id="what-is-a-programming-language">What is a programming language?</h2>
<p>A <strong>programming language</strong> is a way of communicating a set of instructions to a computer. Like human languages such as English, a programming language consists of a set of allowed words and the rules for putting those words together to form phrases with a coherent meaning.<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote"> In your past learning of a (human) language, youve likely referred to these rules as the <em>grammar</em> of a language.</span> Unlike human languages, a programming language must be precise enough to be understood by a computer, and so operates with a relatively small set of words and very structured rules for putting them together. Learning a programming language can be frustrating at first, because even a slight deviation from these rules results in the computer being unable to comprehend what weve written. But our time and efforts spent mastering the rules of a programming language yield a wonderful reward: the computer will not just understand what were saying, but faithfully execute them.</p>
<p>A <strong>program</strong> is simply the text of the instructions we wish to instruct the computer to execute; we call this text program <strong>code</strong> to differentiate it from other forms of text. To write programs in a particular language, we need to understand two key properties of the language. The first is the <strong>syntax</strong> of a programming language, which is the name we give to the rules governing what constitutes a valid program in the language. Before a computer can execute a program, it must read the instructions for the program; the syntax of the programming language specifies the format of these instructions. The second concept is the <strong>semantics</strong> of a programming language, which refers to the rules governing the <em>meaning</em> of different instructions in the language. Once the computer has read the instructions in a program, it begins executing them. The language semantics specifies what the computer should do for each instruction.</p>
<h2 id="the-python-programming-language">The Python programming language</h2>
<p>Just as there are thousands of human languages in the world today, each with their own vocabulary, grammar, and stylistic conventions, so too is there a plethora of programming languages that we can choose from. In this course, well use the Python programming language, which offers a simple, beginner-friendly syntax and a set of language instructions whose semantics are both powerful and accessible.</p>
<p>Now, neither our computer hardware nor operating system understand the Python programming language. Instead, the creators of the Python language developed a program called the <strong>Python interpreter</strong>, whose job is to take programs written in the Python language and execute the instructions.<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote"> So when you “download Python”, what youre actually downloading and installing is this Python interpreter software.</span> You can think of the Python interpreter as a mediator between you the programmer, writing communicating in Python, and the computer hardware that actually executes instructions.</p>
<p>There are two ways of writing code in the Python language to be understood by the interpreter. The first is to write full programs in the Python language, saving them as text files,<label for="sn-2" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-2" class="margin-toggle"/><span class="sidenote"> Python programs use the <code>.py</code> file extension to distinguish them from other text files.</span> and then running them through the Python interpreter. This is the standard way of writing programs: write the instructions, and then run them with the interpreter. The second way is to run the Python interpreter in an interactive mode, which we call the <strong>Python console</strong> or <strong>Python shell</strong>. In this mode, we can write small fragments of Python code and ask the Python interpreter to execute each fragment one at a time. The Python console is useful for experimenting and exploring the language, as you get feedback after every single instruction. The drawback is that interactions with the interpreter in the Python console are ephemeral, lost every time you restart the console. So well use the following approach through the course: <em>use the Python console to learn about and experiment with the Python language, and write full programs in <code>.py</code> files</em>.</p>
<div class="fullwidth">
<p><video src="videos/python_console_demo.webm" autoplay="true" muted="true" loop="true" controls=""><a href="videos/python_console_demo.webm">Python console Demo</a></video><br />
</p>
</div>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>
@@ -0,0 +1,423 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>1.3 Representing Data in Python</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<link rel="stylesheet" href="../tufte.css" />
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<div style="display:none">
\(
\newcommand{\NOT}{\neg}
\newcommand{\AND}{\wedge}
\newcommand{\OR}{\vee}
\newcommand{\XOR}{\oplus}
\newcommand{\IMP}{\Rightarrow}
\newcommand{\IFF}{\Leftrightarrow}
\newcommand{\TRUE}{\text{True}\xspace}
\newcommand{\FALSE}{\text{False}\xspace}
\newcommand{\IN}{\,{\in}\,}
\newcommand{\NOTIN}{\,{\notin}\,}
\newcommand{\TO}{\rightarrow}
\newcommand{\DIV}{\mid}
\newcommand{\NDIV}{\nmid}
\newcommand{\MOD}[1]{\pmod{#1}}
\newcommand{\MODS}[1]{\ (\text{mod}\ #1)}
\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\C}{\mathbb C}
\newcommand{\cA}{\mathcal A}
\newcommand{\cB}{\mathcal B}
\newcommand{\cC}{\mathcal C}
\newcommand{\cD}{\mathcal D}
\newcommand{\cE}{\mathcal E}
\newcommand{\cF}{\mathcal F}
\newcommand{\cG}{\mathcal G}
\newcommand{\cH}{\mathcal H}
\newcommand{\cI}{\mathcal I}
\newcommand{\cJ}{\mathcal J}
\newcommand{\cL}{\mathcal L}
\newcommand{\cK}{\mathcal K}
\newcommand{\cN}{\mathcal N}
\newcommand{\cO}{\mathcal O}
\newcommand{\cP}{\mathcal P}
\newcommand{\cQ}{\mathcal Q}
\newcommand{\cS}{\mathcal S}
\newcommand{\cT}{\mathcal T}
\newcommand{\cV}{\mathcal V}
\newcommand{\cW}{\mathcal W}
\newcommand{\cZ}{\mathcal Z}
\newcommand{\emp}{\emptyset}
\newcommand{\bs}{\backslash}
\newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor}
\newcommand{\ceil}[1]{\left \lceil #1 \right \rceil}
\newcommand{\abs}[1]{\left | #1 \right |}
\newcommand{\xspace}{}
\newcommand{\proofheader}[1]{\underline{\textbf{#1}}}
\)
</div>
<header id="title-block-header">
<h1 class="title">1.3 Representing Data in Python</h1>
</header>
<section>
<p>Data is all around us, but so are computers. If decisions must be data-driven then computers are an excellent tool for processing that data. Especially when we consider that computers are several orders of magnitude faster at computing data than a human. The problem is that computers need to be told exactly <em>how</em> to process the data, and we can do so using one of several programming languages. In this section, we see how data types are represented in Python and how we can use Python to perform operations for us. Well learn about some subtle, but crucial, differences between our theoretical definitions of data types from Section 1.1 and what Python can actually represent. But first, well introduce some general terminology for using the interactive Python console.</p>
<h2 id="the-python-console">The Python console</h2>
<p>When we first start the Python console, we see the following:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1"></a><span class="op">&gt;&gt;&gt;</span></span></code></pre></div>
<p>The text <code>&gt;&gt;&gt;</code> is called the Python <strong>prompt</strong>: the console is “prompting” us to type in some Python code to execute. If we type in a simple arithmetic expression,</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">+</span> <span class="dv">5</span></span></code></pre></div>
<p>and press Enter, we see the following output:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">+</span> <span class="dv">5</span></span>
<span id="cb3-2"><a href="#cb3-2"></a><span class="dv">9</span></span></code></pre></div>
<p>The interpreter took our bit of code, <code>4 + 5</code>, and calculated its value, <code>9</code>. A piece of Python code that produces a value is called an <strong>expression</strong>, and the act of calculating the value of an expression is called <strong>evaluating</strong> the expression.</p>
<p>The expression <code>4 + 5</code> looks simple enough, but technically it is formed from two smaller expressions—the numbers <code>4</code> and <code>5</code> themselves. We can ask <code>Python</code> to evaluate each of these, though the result is not very interesting.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span></span>
<span id="cb4-2"><a href="#cb4-2"></a><span class="dv">4</span></span>
<span id="cb4-3"><a href="#cb4-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">5</span></span>
<span id="cb4-4"><a href="#cb4-4"></a><span class="dv">5</span></span></code></pre></div>
<p>A Python <strong>literal</strong> is the simplest kind of Python expression: it is a piece of code that represents the exact value as written. For example, <code>4</code> is an integer literal representing the number 4.</p>
<p>To sum up,<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote">The pun was not originally intended, but we are pointing it out…</span> the expression <code>4 + 5</code> consists of two smaller expressions, the literals <code>4</code> and <code>5</code>, joined together with the arithmetic operator <code>+</code>, representing addition. Well devote the rest of this section to exploring the different kinds of data types we can use in Python: both how to write their literals, and what operations we can perform on them.</p>
<h2 id="numeric-data-in-python-int-float">Numeric data in Python (<code>int</code>, <code>float</code>)</h2>
<p>Python has two data types for representing numeric data: <code>int</code> and <code>float</code>. Lets start with <code>int</code>, which stands for “integer”, and is the data type that Python uses to represent integers.</p>
<p>An <code>int</code> literal is simply the number as a sequence of digits with an optional <code>-</code> sign, like <code>110</code> or <code>-3421</code>.</p>
<p>Python supports all of the arithmetic operations we discussed in Section 1.1. Here are some examples; try typing them into the Python console yourself to follow along!</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">2</span> <span class="op">+</span> <span class="dv">3</span></span>
<span id="cb5-2"><a href="#cb5-2"></a><span class="dv">5</span></span>
<span id="cb5-3"><a href="#cb5-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">2</span> <span class="op">-</span> <span class="dv">5</span></span>
<span id="cb5-4"><a href="#cb5-4"></a><span class="op">-</span><span class="dv">3</span></span>
<span id="cb5-5"><a href="#cb5-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="op">-</span><span class="dv">2</span> <span class="op">*</span> <span class="dv">10</span></span>
<span id="cb5-6"><a href="#cb5-6"></a><span class="op">-</span><span class="dv">20</span></span>
<span id="cb5-7"><a href="#cb5-7"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">2</span> <span class="op">**</span> <span class="dv">5</span> <span class="co"># This is &quot;2 to the power of 5&quot;</span></span>
<span id="cb5-8"><a href="#cb5-8"></a><span class="dv">32</span></span></code></pre></div>
<p>In the last prompt, we included some additional text—<code># This is "2 to the power of 5"</code>. In Python, we use the character <code>#</code> in code to begin a <strong>comment</strong>, which is code that is ignored by the Python interpreter. Comments are only meant for humans to read, and are a useful way of providing additional information about some Python code. We used it above to explain the meaning of the <code>**</code> operator in our demo.</p>
<p>Python supports the standard precedence rules for arithmetic operations,<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote">sometimes referred to as “BEDMAS” or “PEMDAS”</span> performing exponentiation before multiplication, and multiplication before addition and subtraction:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">1</span> <span class="op">+</span> <span class="dv">2</span> <span class="op">**</span> <span class="dv">3</span> <span class="op">*</span> <span class="dv">5</span> <span class="co"># Equal to &quot;1 plus ((2 to the power of 3) times 5)&quot;</span></span>
<span id="cb6-2"><a href="#cb6-2"></a><span class="dv">41</span></span></code></pre></div>
<p>Just like in mathematics, long expressions like this one can be hard to read. So Python also allows you to use parentheses to group expressions together:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">1</span> <span class="op">+</span> ((<span class="dv">2</span> <span class="op">**</span> <span class="dv">3</span>) <span class="op">*</span> <span class="dv">5</span>) <span class="co"># Equivalent to the previous expression</span></span>
<span id="cb7-2"><a href="#cb7-2"></a><span class="dv">41</span></span>
<span id="cb7-3"><a href="#cb7-3"></a><span class="op">&gt;&gt;&gt;</span> (<span class="dv">1</span> <span class="op">+</span> <span class="dv">2</span>) <span class="op">**</span> (<span class="dv">3</span> <span class="op">*</span> <span class="dv">5</span>) <span class="co"># Different grouping: &quot;(1 plus 2) to the power of (3 times 5)&quot;</span></span>
<span id="cb7-4"><a href="#cb7-4"></a><span class="dv">14348907</span></span></code></pre></div>
<p>When we add, subtract, multiply, and use exponentiation on two integers, the result is always an integer, and so Python always produces an <code>int</code> value for these operations. But <em>dividing</em> two integers certainly doesnt always produce an integer—what does Python do in this case? It turns out that Python has two different forms of division. The first is the operator <code>//</code>, and is called <strong>floor division</strong> (or sometimes <strong>integer division</strong>). For two integers <code>x</code> and <code>y</code>, the result of <code>x // y</code> is equal to the quotient <span class="math inline">\(\frac{\texttt{x}}{\texttt{y}}\)</span>, rounded down to the nearest integer. Here are some examples:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">6</span> <span class="op">//</span> <span class="dv">2</span></span>
<span id="cb8-2"><a href="#cb8-2"></a><span class="dv">3</span></span>
<span id="cb8-3"><a href="#cb8-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">15</span> <span class="op">//</span> <span class="dv">2</span> <span class="co"># 15 ÷ 2 = 7.5, and // rounds down</span></span>
<span id="cb8-4"><a href="#cb8-4"></a><span class="dv">7</span></span>
<span id="cb8-5"><a href="#cb8-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="op">-</span><span class="dv">15</span> <span class="op">//</span> <span class="dv">2</span> <span class="co"># Careful! -15 ÷ 2 = -7.5, which rounds down to -8</span></span>
<span id="cb8-6"><a href="#cb8-6"></a><span class="op">-</span><span class="dv">8</span></span></code></pre></div>
<p>But what about “real” division? This is done using the division operator <code>/</code>:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">5</span> <span class="op">/</span> <span class="dv">2</span></span>
<span id="cb9-2"><a href="#cb9-2"></a><span class="fl">2.5</span></span></code></pre></div>
<p>This returns <code>2.5</code>, which is a value of Pythons <code>float</code> type, which Python uses to represent arbitrary real numbers. A <code>float</code> literal is written as a sequence of digits followed by a decimal point (<code>.</code>) and then another sequence of digits. <code>2.5</code>, <code>.123</code>, and <code>1000.00000001</code> are all examples of <code>float</code> literals.</p>
<p>All of the arithemtic operations weve looked at so far work with <code>float</code> values too:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="fl">3.5</span> <span class="op">+</span> <span class="fl">2.4</span></span>
<span id="cb10-2"><a href="#cb10-2"></a><span class="fl">5.9</span></span>
<span id="cb10-3"><a href="#cb10-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="fl">3.5</span> <span class="op">-</span> <span class="fl">20.9</span></span>
<span id="cb10-4"><a href="#cb10-4"></a><span class="op">-</span><span class="fl">17.4</span></span>
<span id="cb10-5"><a href="#cb10-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="fl">3.5</span> <span class="op">*</span> <span class="fl">2.5</span></span>
<span id="cb10-6"><a href="#cb10-6"></a><span class="fl">8.75</span></span>
<span id="cb10-7"><a href="#cb10-7"></a><span class="op">&gt;&gt;&gt;</span> <span class="fl">3.5</span> <span class="op">/</span> <span class="fl">2.5</span></span>
<span id="cb10-8"><a href="#cb10-8"></a><span class="fl">1.4</span></span>
<span id="cb10-9"><a href="#cb10-9"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">2</span> <span class="op">**</span> <span class="fl">0.5</span></span>
<span id="cb10-10"><a href="#cb10-10"></a><span class="fl">1.4142135623730951</span></span></code></pre></div>
<p>The last expression, <code>2 ** 0.5</code>, calculates the square root of 2. However, this actually poses a problem for Python: since <span class="math inline">\(\sqrt 2\)</span> is an irrational number, its decimal expansion is infinite, and so it cannot be represented in any finite amount of computer memory.<label for="sn-2" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-2" class="margin-toggle"/><span class="sidenote"> More precisely, computers use a binary system where all data, including numbers, are represented as a sequence of 0s and 1s. This sequence of 0s and 1s is finite since computer memory is finite, and so cannot exactly represent <span class="math inline">\(\sqrt 2\)</span>. We will discuss this binary representation of numbers later this year.</span></p>
<p>] The <code>float</code> value thats produced, <code>1.4142135623730951</code>, is an approximation of <span class="math inline">\(\sqrt 2\)</span>, but is not equal to it. Lets see what happens if we try to square it:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="fl">1.4142135623730951</span> <span class="op">*</span> <span class="fl">1.4142135623730951</span></span>
<span id="cb11-2"><a href="#cb11-2"></a><span class="fl">2.0000000000000004</span></span></code></pre></div>
<p>This illustrates a fundamental limitation of <code>float</code>: this data type is used to represent real numbers, but cannot always represent them exactly. Rather, a <code>float</code> value <em>approximates</em> the value of the real number; sometimes that approximation is exact, like <code>2.5</code>, but most of the time it isnt.</p>
<h3 id="vs.-3.0"><code>3</code> vs. <code>3.0</code></h3>
<p>Heres an oddity:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">6</span> <span class="op">//</span> <span class="dv">2</span></span>
<span id="cb12-2"><a href="#cb12-2"></a><span class="dv">3</span></span>
<span id="cb12-3"><a href="#cb12-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">6</span> <span class="op">/</span> <span class="dv">2</span></span>
<span id="cb12-4"><a href="#cb12-4"></a><span class="fl">3.0</span></span></code></pre></div>
<p>Even though <span class="math inline">\(\frac{6}{2}\)</span> is mathematically an integer, the results of the division using <code>//</code> and <code>/</code> are subtly different in Python. When <code>x</code> and <code>y</code> are <code>int</code>s, <code>x // y</code> <em>always</em> evaluates to an <code>int</code>, and <code>x / y</code> <em>always</em> evaluates to a <code>float</code>, even if the value of <span class="math inline">\(\frac{\texttt{x}}{\texttt{y}}\)</span> is an integer! So <code>6 // 2</code> has value <code>3</code>, but <code>6 / 2</code> has value <code>3.0</code>. These two values represent the same mathematical quantity—the number 3—but are stored as different data types in Python, something well explore more later in this course when we study how <code>int</code>s and <code>float</code>s actually work in Python.</p>
<h3 id="mixing-ints-and-floats">Mixing <code>int</code>s and <code>float</code>s</h3>
<p>So to summarize: for two <code>int</code>s <code>x</code> and <code>y</code>, <code>x + y</code>, <code>x - y</code>, <code>x * y</code>, <code>x // y</code>, and <code>x ** y</code> all produce <code>int</code>s, and <code>x / y</code> always produces a <code>float</code>. For two <code>float</code>s, its even simpler: all six of these arithmetic operations produce a <code>float</code>.<label for="sn-3" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-3" class="margin-toggle"/><span class="sidenote">Even <code>//</code>. Try it!</span></p>
<p>But what happens when we mix these two types? <em>An arithmetic operation that is given one <code>int</code> and one <code>float</code> always produces a <code>float</code>.</em> You can think of a <code>float</code> as a parasite—even in long arithmetic expressions where only one value is a <code>float</code>, the whole expression will evaluate to a <code>float</code>.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">12</span> <span class="op">-</span> <span class="dv">4</span> <span class="op">*</span> <span class="dv">5</span> <span class="op">//</span> (<span class="fl">3.0</span> <span class="op">**</span> <span class="dv">2</span>) <span class="op">+</span> <span class="dv">100</span></span>
<span id="cb13-2"><a href="#cb13-2"></a><span class="fl">110.0</span></span></code></pre></div>
<table>
<thead>
<tr class="header">
<th>Operation</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>a + b</code></td>
<td>Returns the sum of the <code>a</code> and <code>b</code></td>
</tr>
<tr class="even">
<td><code>a - b</code></td>
<td>Returns the result of subtraction of <code>b</code> from <code>a</code></td>
</tr>
<tr class="odd">
<td><code>a * b</code></td>
<td>Returns the result of multiplying <code>a</code> by <code>b</code></td>
</tr>
<tr class="even">
<td><code>a / b</code></td>
<td>Return the result of dividing <code>a</code> by <code>b</code></td>
</tr>
<tr class="odd">
<td><code>a % b</code></td>
<td>Return the remainder when <code>a</code> is divided by <code>b</code></td>
</tr>
<tr class="even">
<td><code>a ** b</code></td>
<td>Return the result of <code>a</code> being raised to the power of <code>b</code></td>
</tr>
<tr class="odd">
<td><code>a // b</code></td>
<td>Return the floored division <code>a</code> / <code>b</code></td>
</tr>
</tbody>
</table>
<h3 id="comparison-operators">Comparison operators</h3>
<p>Finally, the numeric comparison operators are represented in Python as follows:</p>
<table>
<thead>
<tr class="header">
<th>Operation</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>a == b</code></td>
<td>Returns whether <code>a</code> and <code>b</code> are equal.</td>
</tr>
<tr class="even">
<td><code>a != b</code></td>
<td>Returns whether <code>a</code> and <code>b</code> are <em>not</em> equal (opposite of <code>==</code>).</td>
</tr>
<tr class="odd">
<td><code>a &gt; b</code></td>
<td>Returns whether <code>a</code> is greater than the value of <code>b</code>.</td>
</tr>
<tr class="even">
<td><code>a &lt; b</code></td>
<td>Returns whether <code>a</code> is less than the value of <code>b</code>.</td>
</tr>
<tr class="odd">
<td><code>a &gt;= b</code></td>
<td>Returns whether <code>a</code> is greater than or equal to <code>b</code>.</td>
</tr>
<tr class="even">
<td><code>a &lt;= b</code></td>
<td>Returns whether <code>a</code> is less than or equal to the value <code>b</code>.</td>
</tr>
</tbody>
</table>
<p>Here are a few examples:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb14-1"><a href="#cb14-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">==</span> <span class="dv">4</span></span>
<span id="cb14-2"><a href="#cb14-2"></a><span class="va">True</span></span>
<span id="cb14-3"><a href="#cb14-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">!=</span> <span class="dv">6</span></span>
<span id="cb14-4"><a href="#cb14-4"></a><span class="va">True</span></span>
<span id="cb14-5"><a href="#cb14-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">&lt;</span> <span class="dv">2</span></span>
<span id="cb14-6"><a href="#cb14-6"></a><span class="va">False</span></span>
<span id="cb14-7"><a href="#cb14-7"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">&gt;=</span> <span class="dv">1</span></span>
<span id="cb14-8"><a href="#cb14-8"></a><span class="va">True</span></span></code></pre></div>
<p>And returning to our discussion earlier, we can see that even though <code>int</code>s and <code>float</code>s are different types, Python can recognize when their values represent the exact same number:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">4</span> <span class="op">==</span> <span class="fl">4.0</span></span>
<span id="cb15-2"><a href="#cb15-2"></a><span class="va">True</span></span></code></pre></div>
<p>In these examples, weve seen the values <code>True</code> and <code>False</code> produced as a result of these comparison expressions. You can probably tell exactly what they mean, but lets take a moment to introduce them formally.</p>
<h2 id="boolean-data-in-python-bool">Boolean data in Python (<code>bool</code>)</h2>
<p>In Python, boolean data is represented using the data type <code>bool</code>. Unlike the broad range of numbers we just saw, there are only two literal values of type <code>bool</code>: <code>True</code> and <code>False</code>.</p>
<p>There are three boolean operators we can perform on boolean values: <code>not</code>, <code>and</code>, and <code>or</code>.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="kw">not</span> <span class="va">True</span></span>
<span id="cb16-2"><a href="#cb16-2"></a><span class="va">False</span></span>
<span id="cb16-3"><a href="#cb16-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="va">True</span> <span class="kw">and</span> <span class="va">True</span></span>
<span id="cb16-4"><a href="#cb16-4"></a><span class="va">True</span></span>
<span id="cb16-5"><a href="#cb16-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="va">True</span> <span class="kw">and</span> <span class="va">False</span></span>
<span id="cb16-6"><a href="#cb16-6"></a><span class="va">False</span></span>
<span id="cb16-7"><a href="#cb16-7"></a><span class="op">&gt;&gt;&gt;</span> <span class="va">False</span> <span class="kw">or</span> <span class="va">True</span></span>
<span id="cb16-8"><a href="#cb16-8"></a><span class="va">True</span></span>
<span id="cb16-9"><a href="#cb16-9"></a><span class="op">&gt;&gt;&gt;</span> <span class="va">False</span> <span class="kw">or</span> <span class="va">False</span></span>
<span id="cb16-10"><a href="#cb16-10"></a><span class="va">False</span></span></code></pre></div>
<p>One note about the <code>or</code> operator in Python is that it is the <strong>inclusive or</strong>, meaning it produces <code>True</code> when both of its operand expressions are <code>True</code>.</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="va">True</span> <span class="kw">or</span> <span class="va">True</span></span>
<span id="cb17-2"><a href="#cb17-2"></a><span class="va">True</span></span></code></pre></div>
<p>Just as we saw how arithmetic operator expressions can be nested within each other, we can combine boolean operator expressions, and even the arithmetic comparison operators:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="va">True</span> <span class="kw">and</span> (<span class="va">False</span> <span class="kw">or</span> <span class="va">True</span>)</span>
<span id="cb18-2"><a href="#cb18-2"></a><span class="va">True</span></span>
<span id="cb18-3"><a href="#cb18-3"></a><span class="op">&gt;&gt;&gt;</span> (<span class="dv">3</span> <span class="op">==</span> <span class="dv">4</span>) <span class="kw">or</span> (<span class="dv">5</span> <span class="op">&gt;</span> <span class="dv">10</span>)</span>
<span id="cb18-4"><a href="#cb18-4"></a><span class="va">False</span></span></code></pre></div>
<h2 id="textual-data-in-python-str">Textual data in Python (<code>str</code>)</h2>
<p>All Python code is text that we type into the computer, so how do we distinguish between text thats code and text thats data, like a persons name? Python uses the <code>str</code> (short for “string”) data type to represent textual data. A <code>str</code> literal is a sequence of characters surrounded by single-quotes (<code>'</code>).<label for="sn-4" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-4" class="margin-toggle"/><span class="sidenote"> Python allows string literals to be written using either single-quotes or double-qutoes (<code>"</code>). Well tend to use single-quotes in this course to match how Python displays strings, as well see in this section.</span> For example, we could write this courses name in Python as the string literal <code>'Foundations of Computer Science I'</code>.</p>
<!--
A common introductory string literal is `'Hello, World!'`.
But what happens when we would like to use the single-quote as an apostrophe inside the string literal?
For example, `David's Tea` cannot simply be written as `'David's Tea'` because the apostrophe would mark the end of the string literal.
To overcome this issue we could, of course, simply use double-quotes: `"David's Tea"`.
But another option is to use the **escape character** `\`.
This allows us to *escape* the typical meaning of a single-quote (i.e., to mark the end of the string literal).
Thus, we could write `David's Tea` as: `'David\'s Tea`.
The combination of the escape character and the following character is called an **escape sequence**.
There are many different kinds of escape sequences in Python that can be used with string literals.
We will not enumerate them here, but it is useful to keep a mental note of new escape sequences you come across while reading code.
-->
<p>Now lets see what kinds of operations we can perform on strings. First, we can compare strings using <code>==</code>, just like we can for <code>int</code>s and <code>float</code>s:</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb19-1"><a href="#cb19-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;David&#39;</span> <span class="op">==</span> <span class="st">&#39;David&#39;</span></span>
<span id="cb19-2"><a href="#cb19-2"></a><span class="va">True</span></span>
<span id="cb19-3"><a href="#cb19-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;David&#39;</span> <span class="op">==</span> <span class="st">&#39;david&#39;</span> <span class="co"># String comparisons are case-sensitive</span></span>
<span id="cb19-4"><a href="#cb19-4"></a><span class="va">False</span></span></code></pre></div>
<p>Python supports <strong>string indexing</strong> to extract a single character from a string.<label for="sn-5" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-5" class="margin-toggle"/><span class="sidenote"> Remember, string indexing starts at 0. <code>s[0]</code> represents the <em>first</em> character in the string <code>s</code>.</span></p>
<div class="sourceCode" id="cb20"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;David&#39;</span>[<span class="dv">0</span>]</span>
<span id="cb20-2"><a href="#cb20-2"></a><span class="co">&#39;D&#39;</span></span>
<span id="cb20-3"><a href="#cb20-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;David&#39;</span>[<span class="dv">3</span>]</span>
<span id="cb20-4"><a href="#cb20-4"></a><span class="co">&#39;i&#39;</span></span></code></pre></div>
<p>And Python supports <strong>concatenation</strong> using the familiar <code>+</code> operator:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb21-1"><a href="#cb21-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;One string&#39;</span> <span class="op">+</span> <span class="st">&#39;to rule them all.&#39;</span></span>
<span id="cb21-2"><a href="#cb21-2"></a><span class="co">&#39;One stringto rule them all.&#39;</span></span>
<span id="cb21-3"><a href="#cb21-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;One string &#39;</span> <span class="op">+</span> <span class="st">&#39;to rule them all.&#39;</span> <span class="co"># Note the extra space!</span></span>
<span id="cb21-4"><a href="#cb21-4"></a><span class="co">&#39;One string to rule them all.&#39;</span></span></code></pre></div>
<p>One operation that we did not cover in Section 1.1 is a fun quirk of Python: string repetition.</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;David&#39;</span> <span class="op">*</span> <span class="dv">3</span></span>
<span id="cb22-2"><a href="#cb22-2"></a><span class="co">&#39;DavidDavidDavid&#39;</span></span></code></pre></div>
<p>And of course, all of these string operation expressions can be nested within each other:</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb23-1"><a href="#cb23-1"></a><span class="op">&gt;&gt;&gt;</span> (<span class="st">&#39;David&#39;</span> <span class="op">+</span> <span class="st">&#39;Mario&#39;</span>) <span class="op">*</span> <span class="dv">3</span></span>
<span id="cb23-2"><a href="#cb23-2"></a><span class="co">&#39;DavidMarioDavidMarioDavidMario&#39;</span></span></code></pre></div>
<h2 id="set-data-in-python-set">Set data in Python (<code>set</code>)</h2>
<p>Python uses the <code>set</code> data type to store set data. A <code>set</code> literal matches the notation we use in mathematics: the literal begins with a <code>{</code> and ends with a <code>}</code>, and each element of the list is written inside the braces, separated from each other by commas. For example, <code>{1, 2, 3}</code> is a set of <code>int</code>s, and <code>{1, 2.0, 'three'}</code> is a set of elements of mixed types.</p>
<p>Like other data types, sets can be compared for equality using <code>==</code>. Remember that element order does not matter when comparing sets!</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb24-1"><a href="#cb24-1"></a><span class="op">&gt;&gt;&gt;</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>} <span class="op">==</span> {<span class="dv">3</span>, <span class="dv">1</span>, <span class="dv">2</span>}</span>
<span id="cb24-2"><a href="#cb24-2"></a><span class="va">True</span></span></code></pre></div>
<p>Python also supports the “element of” (<span class="math inline">\(\in\)</span>) set operation using the <code>in</code> operator.</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb25-1"><a href="#cb25-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">1</span> <span class="kw">in</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>}</span>
<span id="cb25-2"><a href="#cb25-2"></a><span class="va">True</span></span>
<span id="cb25-3"><a href="#cb25-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">10</span> <span class="kw">in</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>}</span>
<span id="cb25-4"><a href="#cb25-4"></a><span class="va">False</span></span></code></pre></div>
<p>Python also allows <code>not</code> and <code>in</code> to be combined to form an operator that corresponds to the set operation <span class="math inline">\(\notin\)</span>:</p>
<div class="sourceCode" id="cb26"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb26-1"><a href="#cb26-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">1</span> <span class="kw">not</span> <span class="kw">in</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>}</span>
<span id="cb26-2"><a href="#cb26-2"></a><span class="va">False</span></span>
<span id="cb26-3"><a href="#cb26-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">10</span> <span class="kw">not</span> <span class="kw">in</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>}</span>
<span id="cb26-4"><a href="#cb26-4"></a><span class="va">True</span></span></code></pre></div>
<p>Well see in the next chapter how other set operations such as union and intersection are supported in Python.</p>
<h2 id="list-data-in-python-list-tuple">List data in Python (<code>list</code>, <code>tuple</code>)</h2>
<p>Python uses two different data types to store list data: <code>list</code> and <code>tuple</code>. <code>list</code> literals are written the same way as <code>set</code> literals, except using square brackets instead of curly braces. Lists support the same operations we saw for strings and sets earlier:</p>
<div class="sourceCode" id="cb27"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb27-1"><a href="#cb27-1"></a><span class="op">&gt;&gt;&gt;</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>] <span class="op">==</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>] <span class="co"># List equality comparison; order matters!</span></span>
<span id="cb27-2"><a href="#cb27-2"></a><span class="va">True</span></span>
<span id="cb27-3"><a href="#cb27-3"></a><span class="op">&gt;&gt;&gt;</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>] <span class="op">==</span> [<span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>]</span>
<span id="cb27-4"><a href="#cb27-4"></a><span class="va">False</span></span>
<span id="cb27-5"><a href="#cb27-5"></a><span class="op">&gt;&gt;&gt;</span> ([<span class="st">&#39;David&#39;</span>, <span class="st">&#39;Mario&#39;</span>, <span class="st">&#39;Jacqueline&#39;</span>, <span class="st">&#39;Diane&#39;</span>])[<span class="dv">0</span>] <span class="co"># List indexing</span></span>
<span id="cb27-6"><a href="#cb27-6"></a><span class="co">&#39;David&#39;</span></span>
<span id="cb27-7"><a href="#cb27-7"></a><span class="op">&gt;&gt;&gt;</span> [<span class="st">&#39;David&#39;</span>, <span class="st">&#39;Mario&#39;</span>] <span class="op">+</span> [<span class="st">&#39;Jacqueline&#39;</span>, <span class="st">&#39;Diane&#39;</span>] <span class="co"># List concatenation</span></span>
<span id="cb27-8"><a href="#cb27-8"></a>[<span class="st">&#39;David&#39;</span>, <span class="st">&#39;Mario&#39;</span>, <span class="st">&#39;Jacqueline&#39;</span>, <span class="st">&#39;Diane&#39;</span>]</span>
<span id="cb27-9"><a href="#cb27-9"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">1</span> <span class="kw">in</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>] <span class="co"># List &quot;element of&quot; operation</span></span>
<span id="cb27-10"><a href="#cb27-10"></a><span class="va">True</span></span></code></pre></div>
<p><code>tuple</code> literals are written using regular parentheses instead, but otherwise support the above operations as well.</p>
<div class="sourceCode" id="cb28"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb28-1"><a href="#cb28-1"></a><span class="op">&gt;&gt;&gt;</span> (<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>) <span class="op">==</span> (<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>) <span class="co"># Tuple equality comparison</span></span>
<span id="cb28-2"><a href="#cb28-2"></a><span class="va">True</span></span>
<span id="cb28-3"><a href="#cb28-3"></a><span class="op">&gt;&gt;&gt;</span> (<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>) <span class="op">==</span> (<span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>)</span>
<span id="cb28-4"><a href="#cb28-4"></a><span class="va">False</span></span>
<span id="cb28-5"><a href="#cb28-5"></a><span class="op">&gt;&gt;&gt;</span> (<span class="st">&#39;David&#39;</span>, <span class="st">&#39;Mario&#39;</span>, <span class="st">&#39;Jacqueline&#39;</span>, <span class="st">&#39;Diane&#39;</span>)[<span class="dv">0</span>] <span class="co"># Tuple indexing</span></span>
<span id="cb28-6"><a href="#cb28-6"></a><span class="co">&#39;David&#39;</span></span>
<span id="cb28-7"><a href="#cb28-7"></a><span class="op">&gt;&gt;&gt;</span> (<span class="st">&#39;David&#39;</span>, <span class="st">&#39;Mario&#39;</span>) <span class="op">+</span> (<span class="st">&#39;Jacqueline&#39;</span>, <span class="st">&#39;Diane&#39;</span>) <span class="co"># Tuple concatenation</span></span>
<span id="cb28-8"><a href="#cb28-8"></a>(<span class="st">&#39;David&#39;</span>, <span class="st">&#39;Mario&#39;</span>, <span class="st">&#39;Jacqueline&#39;</span>, <span class="st">&#39;Diane&#39;</span>)</span>
<span id="cb28-9"><a href="#cb28-9"></a><span class="op">&gt;&gt;&gt;</span> <span class="dv">1</span> <span class="kw">in</span> (<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>) <span class="co"># Tuple &quot;element of&quot; operation</span></span>
<span id="cb28-10"><a href="#cb28-10"></a><span class="va">True</span></span></code></pre></div>
<p>So why does Python have two different data types that represent the same kind of data? There is an important technical distinction between <code>list</code> and <code>tuple</code> that well learn about later in this course, but for now well generally stick with <code>list</code>.</p>
<h2 id="mapping-data-in-python-dict">Mapping data in Python (<code>dict</code>)</h2>
<p>Python stores mapping data using a data type called <code>dict</code>, short for “dictionary”. <code>dict</code> literals are written similarly to sets, with each key-value pair separated by a colon. For example, we can represent the mapping from the previous section with the dictionary literal <code>{'fries': 5.99, 'steak': 25.99, 'soup': 8.99}</code>. In this dictionary, the keys are strings, and the values are <code>float</code>s.</p>
<p>But if both sets and dictionaries use curly braces, then does the literal <code>{}</code> represent an empty set or an empty dictionary? The answer (for historical reasons) is an empty dictionary—Python has no literal to represent an empty set.<label for="sn-6" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-6" class="margin-toggle"/><span class="sidenote"> Instead, we represent an empty set with <code>set()</code>, which is syntax we havent yet seen and will explore later.</span></p>
<p>Dictionaries also support equality comparison using <code>==</code>. They support key lookup using the same syntax as string and list indexing:</p>
<div class="sourceCode" id="cb29"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb29-1"><a href="#cb29-1"></a><span class="op">&gt;&gt;&gt;</span> ({<span class="st">&#39;fries&#39;</span>: <span class="fl">5.99</span>, <span class="st">&#39;steak&#39;</span>: <span class="fl">25.99</span>, <span class="st">&#39;soup&#39;</span>: <span class="fl">8.99</span>})[<span class="st">&#39;fries&#39;</span>]</span>
<span id="cb29-2"><a href="#cb29-2"></a><span class="fl">5.99</span></span></code></pre></div>
<p>And finally, they support checking whether a key is present in a dictionary using the <code>in</code> operator:</p>
<div class="sourceCode" id="cb30"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb30-1"><a href="#cb30-1"></a><span class="op">&gt;&gt;&gt;</span> <span class="st">&#39;fries&#39;</span> <span class="kw">in</span> {<span class="st">&#39;fries&#39;</span>: <span class="fl">5.99</span>, <span class="st">&#39;steak&#39;</span>: <span class="fl">25.99</span>, <span class="st">&#39;soup&#39;</span>: <span class="fl">8.99</span>}</span>
<span id="cb30-2"><a href="#cb30-2"></a><span class="va">True</span></span></code></pre></div>
<h2 id="references">References</h2>
<ul>
<li>CSC108 videos: Python as a Calculator (<a href="https://youtu.be/E6aJGrCTlTQ">Part 1</a>, <a href="https://youtu.be/mJqjTh6Srlg">Part 2</a>, <a href="https://youtu.be/LVHjVcMug30">Part 3</a>)</li>
<li>CSC108 videos: Type bool (<a href="https://youtu.be/pTk0QR0KhpU">Part 1</a>, <a href="https://youtu.be/ffRQyyIbyAI">Part 2</a>, <a href="https://youtu.be/U4RQx1_Z-RA">Part 3</a>, <a href="https://youtu.be/h5mocjb3SVE">Part 4</a>)</li>
<li>CSC108 videos: Type str (<a href="https://youtu.be/eMsfkkNg3J4">Part 1</a>, <a href="https://youtu.be/QM2WtjjYgzY">Part 2</a>)</li>
<li><a href="../A-python-builtins/02-types.html">Appendix A.2 Python Built-In Data Types Reference</a></li>
</ul>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>
+212
View File
@@ -0,0 +1,212 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>1.4 Storing Data in Variables</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<link rel="stylesheet" href="../tufte.css" />
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<div style="display:none">
\(
\newcommand{\NOT}{\neg}
\newcommand{\AND}{\wedge}
\newcommand{\OR}{\vee}
\newcommand{\XOR}{\oplus}
\newcommand{\IMP}{\Rightarrow}
\newcommand{\IFF}{\Leftrightarrow}
\newcommand{\TRUE}{\text{True}\xspace}
\newcommand{\FALSE}{\text{False}\xspace}
\newcommand{\IN}{\,{\in}\,}
\newcommand{\NOTIN}{\,{\notin}\,}
\newcommand{\TO}{\rightarrow}
\newcommand{\DIV}{\mid}
\newcommand{\NDIV}{\nmid}
\newcommand{\MOD}[1]{\pmod{#1}}
\newcommand{\MODS}[1]{\ (\text{mod}\ #1)}
\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\C}{\mathbb C}
\newcommand{\cA}{\mathcal A}
\newcommand{\cB}{\mathcal B}
\newcommand{\cC}{\mathcal C}
\newcommand{\cD}{\mathcal D}
\newcommand{\cE}{\mathcal E}
\newcommand{\cF}{\mathcal F}
\newcommand{\cG}{\mathcal G}
\newcommand{\cH}{\mathcal H}
\newcommand{\cI}{\mathcal I}
\newcommand{\cJ}{\mathcal J}
\newcommand{\cL}{\mathcal L}
\newcommand{\cK}{\mathcal K}
\newcommand{\cN}{\mathcal N}
\newcommand{\cO}{\mathcal O}
\newcommand{\cP}{\mathcal P}
\newcommand{\cQ}{\mathcal Q}
\newcommand{\cS}{\mathcal S}
\newcommand{\cT}{\mathcal T}
\newcommand{\cV}{\mathcal V}
\newcommand{\cW}{\mathcal W}
\newcommand{\cZ}{\mathcal Z}
\newcommand{\emp}{\emptyset}
\newcommand{\bs}{\backslash}
\newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor}
\newcommand{\ceil}[1]{\left \lceil #1 \right \rceil}
\newcommand{\abs}[1]{\left | #1 \right |}
\newcommand{\xspace}{}
\newcommand{\proofheader}[1]{\underline{\textbf{#1}}}
\)
</div>
<header id="title-block-header">
<h1 class="title">1.4 Storing Data in Variables</h1>
</header>
<section>
<p>So far, weve been writing expressions in the Python console using only literals and operators. But as the computations we want to perform get more complex, relying on just literals and operators is very cumbersome. We can write very complex nested expressions, but this makes our code very hard to understand.</p>
<p>For example, suppose were given three points in the Cartesian plane <span class="math inline">\((1, 3)\)</span>, <span class="math inline">\((2, 5)\)</span>, <span class="math inline">\((10, -1)\)</span> that form a path, and we want to find the length of this path.</p>
<p><img src="images/0104-diagram-v2.png" alt="Cartesian Plane Diagram" /><br />
</p>
<p>Wed like to use this formula for the distance <span class="math inline">\(d\)</span> between two points <span class="math inline">\((x_1, y_1)\)</span> and <span class="math inline">\((x_2, y_2)\)</span>:</p>
<p><span class="math display">\[ d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}. \]</span></p>
<p>We <em>could</em> write this as a single arithmetic expression and have Python evaluate it:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1"></a><span class="op">&gt;&gt;&gt;</span> ((<span class="dv">1</span> <span class="op">-</span> <span class="dv">2</span>) <span class="op">**</span> <span class="dv">2</span> <span class="op">+</span> (<span class="dv">3</span> <span class="op">-</span> <span class="dv">5</span>) <span class="op">**</span> <span class="dv">2</span>) <span class="op">**</span> <span class="fl">0.5</span> <span class="op">+</span> ((<span class="dv">2</span> <span class="op">-</span> <span class="dv">10</span>) <span class="op">**</span> <span class="dv">2</span> <span class="op">+</span> (<span class="dv">5</span> <span class="op">+</span> <span class="dv">1</span>) <span class="op">**</span> <span class="dv">2</span>) <span class="op">**</span> <span class="fl">0.5</span></span>
<span id="cb1-2"><a href="#cb1-2"></a><span class="fl">12.23606797749979</span></span></code></pre></div>
<p>But typing in this expression is quite error-prone, and hard to understand. Just like in mathematics, we can improve our code by breaking down this problem into intermediate steps. Python (like all other programming languages) gives us a ways to bind values to names, so that we can refer to those values later on in subsequent calculations.</p>
<h2 id="variables">Variables</h2>
<p>A <strong>variable</strong> is a piece of code that is a name that <em>refers</em> to a value. We create variables in Python using the syntax:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1"></a><span class="op">&lt;</span>variable<span class="op">&gt;</span> <span class="op">=</span> <span class="op">&lt;</span>expression<span class="op">&gt;</span></span></code></pre></div>
<p>which is a form of Python code called an <strong>assignment statement</strong>. You might wonder why we use the term “statement” rather than “expression” for assignment. An <em>expression</em> is a piece of Python code that is evaluated to produce a value. When we execute an assignment statement, it doesnt produce a value—it instead defines a variable.</p>
<p>Python executes an assignment statement in two steps:</p>
<ol type="1">
<li>First, the expression on the right-hand side of the <code>=</code> is evaluated, producing a value.</li>
<li>Second, that value is bound to the variable on the left-hand side.</li>
</ol>
<p>After the assignment statement is executed, the variable may be used to refer to the value. Heres how we can use variables to simplify the calculation above:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1"></a><span class="op">&gt;&gt;&gt;</span> distance1 <span class="op">=</span> ((<span class="dv">1</span> <span class="op">-</span> <span class="dv">2</span>) <span class="op">**</span> <span class="dv">2</span> <span class="op">+</span> (<span class="dv">3</span> <span class="op">-</span> <span class="dv">5</span>) <span class="op">**</span> <span class="dv">2</span>) <span class="op">**</span> <span class="fl">0.5</span> <span class="co"># Distance between (1, 3) and (2, 5)</span></span>
<span id="cb3-2"><a href="#cb3-2"></a><span class="op">&gt;&gt;&gt;</span> distance2 <span class="op">=</span> ((<span class="dv">2</span> <span class="op">-</span> <span class="dv">10</span>) <span class="op">**</span> <span class="dv">2</span> <span class="op">+</span> (<span class="dv">5</span> <span class="op">+</span> <span class="dv">1</span>) <span class="op">**</span> <span class="dv">2</span>) <span class="op">**</span> <span class="fl">0.5</span> <span class="co"># Distance between (2, 5) and (10, -1)</span></span>
<span id="cb3-3"><a href="#cb3-3"></a><span class="op">&gt;&gt;&gt;</span> distance1 <span class="co"># A variable is an expression; evaluating it produces the value it refers to</span></span>
<span id="cb3-4"><a href="#cb3-4"></a><span class="fl">2.23606797749979</span></span>
<span id="cb3-5"><a href="#cb3-5"></a><span class="op">&gt;&gt;&gt;</span> distance2</span>
<span id="cb3-6"><a href="#cb3-6"></a><span class="fl">10.0</span></span>
<span id="cb3-7"><a href="#cb3-7"></a><span class="op">&gt;&gt;&gt;</span> distance1 <span class="op">+</span> distance2 <span class="co"># The total distance</span></span>
<span id="cb3-8"><a href="#cb3-8"></a><span class="fl">12.23606797749979</span></span></code></pre></div>
<h2 id="choosing-good-variable-names">Choosing good variable names</h2>
<p>Because variables are used to store intermediate values in computations, it is important to choose good variable names so that you can remember what the purpose of each variable is. This might not seem that important in our above example because there were only two variables, but as you start writing larger programs, youll have to grapple with dozens, if not hundreds, of variables, and choosing good names will be paramount.</p>
<p>For now, well introduce a few simple rules that you should follow when choosing variable names:</p>
<ol type="1">
<li><p>All variable names should use only lowercase letters, digits, and underscores. So <code>distance1</code>, not <code>Distance1</code>.</p></li>
<li><p>When a variable name consists of multiple words, write each word in lowercase and separate them with an underscore.<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote"> You arent allowed to use spaces in variable names.</span> For example, we might create a variable to refer to the total distance by doing</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1"></a><span class="op">&gt;&gt;&gt;</span> total_distance <span class="op">=</span> distance1 <span class="op">+</span> distance2</span></code></pre></div>
<p>We use the name <code>total_distance</code> rather than <code>totaldistance</code> or <code>totalDistance</code> (the latter is a naming style used in other programming languages, but not here).</p></li>
<li><p>Avoid single-letter variable names and non-standard acronyms/abbreviations, outside of some mathematical contexts.</p>
<p>For example, we might have used <code>d1</code> and <code>d2</code> instead of <code>distance1</code> and <code>distance2</code> because <code>d</code> is the variable we used for distance in our above formula. However, we should <em>not</em> use <code>td</code> instead of <code>total_distance</code>, because a second person wouldnt immediately understand what <code>td</code> stands for.</p></li>
</ol>
<h2 id="the-value-based-python-memory-model">The value-based Python memory model</h2>
<p>As our programs get larger, it is useful to have a principled way to keep track of the variables and data used by the programs. A <strong>memory model</strong> is a structured way of representing variables and data in a program.<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote"> The term “memory” here refers to the computer memory used to actually store the data.</span> For the next few weeks, were going to use the <em>value-based Python memory model</em>, which simply uses a table to represent the associations between variables and their associated values. For example, the value-based memory model for our above example is the following:</p>
<div class="memory-model-values">
<table>
<thead>
<tr class="header">
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>distance1</code></td>
<td><code>2.23606797749979</code></td>
</tr>
<tr class="even">
<td><code>distance2</code></td>
<td><code>10.0</code></td>
</tr>
</tbody>
</table>
</div>
<h2 id="references">References</h2>
<ul>
<li>CSC108 videos: Variable Assignment (<a href="https://www.youtube.com/watch?v=E6aJGrCTlTQ">Part 1</a>, <a href="https://www.youtube.com/watch?v=CPmVn_hQzBs">Part 2</a>, <a href="https://www.youtube.com/watch?v=SkWSVsvgxYE">Part 3</a>)</li>
<li>CSC108 videos: Assignment Statement Visualizer (<a href="https://youtu.be/p-h8bDG8VPA">Part 1</a>)</li>
</ul>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>
+189
View File
@@ -0,0 +1,189 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>1.5 Building Up Data with Comprehensions</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<link rel="stylesheet" href="../tufte.css" />
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<div style="display:none">
\(
\newcommand{\NOT}{\neg}
\newcommand{\AND}{\wedge}
\newcommand{\OR}{\vee}
\newcommand{\XOR}{\oplus}
\newcommand{\IMP}{\Rightarrow}
\newcommand{\IFF}{\Leftrightarrow}
\newcommand{\TRUE}{\text{True}\xspace}
\newcommand{\FALSE}{\text{False}\xspace}
\newcommand{\IN}{\,{\in}\,}
\newcommand{\NOTIN}{\,{\notin}\,}
\newcommand{\TO}{\rightarrow}
\newcommand{\DIV}{\mid}
\newcommand{\NDIV}{\nmid}
\newcommand{\MOD}[1]{\pmod{#1}}
\newcommand{\MODS}[1]{\ (\text{mod}\ #1)}
\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\C}{\mathbb C}
\newcommand{\cA}{\mathcal A}
\newcommand{\cB}{\mathcal B}
\newcommand{\cC}{\mathcal C}
\newcommand{\cD}{\mathcal D}
\newcommand{\cE}{\mathcal E}
\newcommand{\cF}{\mathcal F}
\newcommand{\cG}{\mathcal G}
\newcommand{\cH}{\mathcal H}
\newcommand{\cI}{\mathcal I}
\newcommand{\cJ}{\mathcal J}
\newcommand{\cL}{\mathcal L}
\newcommand{\cK}{\mathcal K}
\newcommand{\cN}{\mathcal N}
\newcommand{\cO}{\mathcal O}
\newcommand{\cP}{\mathcal P}
\newcommand{\cQ}{\mathcal Q}
\newcommand{\cS}{\mathcal S}
\newcommand{\cT}{\mathcal T}
\newcommand{\cV}{\mathcal V}
\newcommand{\cW}{\mathcal W}
\newcommand{\cZ}{\mathcal Z}
\newcommand{\emp}{\emptyset}
\newcommand{\bs}{\backslash}
\newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor}
\newcommand{\ceil}[1]{\left \lceil #1 \right \rceil}
\newcommand{\abs}[1]{\left | #1 \right |}
\newcommand{\xspace}{}
\newcommand{\proofheader}[1]{\underline{\textbf{#1}}}
\)
</div>
<header id="title-block-header">
<h1 class="title">1.5 Building Up Data with Comprehensions</h1>
</header>
<section>
<p>To wrap up our introduction to data in Python, were going to learn about one last kind of expression that allows to build up and transform large collections of data in Python.</p>
<h2 id="from-set-builder-notation-to-set-comprehensions">From set builder notation to set comprehensions</h2>
<p>Recall <em>set builder notation</em>, which is a concise way of defining a mathematical set by specifying the values of the elements in terms of a larger domain. For example, suppose we have a set <span class="math inline">\(S = \{1, 2, 3, 4, 5\}\)</span>. We can express a set of squares of the elements of <span class="math inline">\(S\)</span>: <span class="math display">\[\{ x^2 \mid x \in S \}.\]</span></p>
<p>It turns out that this notation translates naturally to Python! To start, lets go into the Python Console and create a variable that refers to a set of numbers:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1"></a><span class="op">&gt;&gt;&gt;</span> numbers <span class="op">=</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>}</span></code></pre></div>
<p>Now, we introduce a new kind of expression called a <strong>set comprehension</strong>, which has the following syntax:<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote"> Careful with this: even though set comprehensions also use curly braces, they are <em>not</em> the same as set literals. We arent writing out the individual elements separated by commas.</span></p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1"></a>{ <span class="op">&lt;</span>expr<span class="op">&gt;</span> <span class="cf">for</span> <span class="op">&lt;</span>variable<span class="op">&gt;</span> <span class="kw">in</span> <span class="op">&lt;</span>collection<span class="op">&gt;</span> }</span></code></pre></div>
<p>Evaluating a set comprehension is done by taking the <code>&lt;expr&gt;</code> and evaluating it once for each value in <code>&lt;collection&gt;</code> assigned to the <code>&lt;variable&gt;</code>. This is exactly analogous to set builder notation, except using <code>for</code> instead of <span class="math inline">\(|\)</span> and <code>in</code> instead of <span class="math inline">\(\in\)</span>. Heres how we can repeat our initial example in Python using a set comprehension:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1"></a><span class="op">&gt;&gt;&gt;</span> {x <span class="op">**</span> <span class="dv">2</span> <span class="cf">for</span> x <span class="kw">in</span> numbers}</span>
<span id="cb3-2"><a href="#cb3-2"></a>{<span class="dv">1</span>, <span class="dv">4</span>, <span class="dv">9</span>, <span class="dv">16</span>, <span class="dv">25</span>}</span></code></pre></div>
<p>Pretty cool, eh? If you arent sure exactly what happened here, its useful to write out the expanded form of the set comprehension:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1"></a> {x <span class="op">**</span> <span class="dv">2</span> <span class="cf">for</span> x <span class="kw">in</span> numbers}</span>
<span id="cb4-2"><a href="#cb4-2"></a><span class="op">==</span> {<span class="dv">1</span> <span class="op">**</span> <span class="dv">2</span>, <span class="dv">2</span> <span class="op">**</span> <span class="dv">2</span>, <span class="dv">3</span> <span class="op">**</span> <span class="dv">2</span>, <span class="dv">4</span> <span class="op">**</span> <span class="dv">2</span>, <span class="dv">5</span> <span class="op">**</span> <span class="dv">2</span>} <span class="co"># Replacing x with 1, 2, 3, 4, and 5.</span></span></code></pre></div>
<p>It goes even further—we can use set comprehensions with a Python list as well.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1"></a><span class="op">&gt;&gt;&gt;</span> {x <span class="op">**</span> <span class="dv">2</span> <span class="cf">for</span> x <span class="kw">in</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>]}</span>
<span id="cb5-2"><a href="#cb5-2"></a>{<span class="dv">1</span>, <span class="dv">4</span>, <span class="dv">9</span>, <span class="dv">16</span>, <span class="dv">25</span>}</span></code></pre></div>
<p>In fact, as well see later in this course, set comprehensions can be used with any “collection” data type in Python, not just sets and lists.</p>
<h2 id="list-and-dictionary-comprehensions">List and dictionary comprehensions</h2>
<p>Even though set comprehensions draw their inspiration from set builder notation in mathematics, Python has extended them to other data types.</p>
<p>A <strong>list comprehension</strong> is very similar to a set comprehension, except its syntax uses square brackets instead of curly braces:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1"></a>[ <span class="op">&lt;</span>expr<span class="op">&gt;</span> <span class="cf">for</span> <span class="op">&lt;</span>variable<span class="op">&gt;</span> <span class="kw">in</span> <span class="op">&lt;</span>collection<span class="op">&gt;</span> ]</span></code></pre></div>
<p>Once again, <code>&lt;collection&gt;</code> can be a set or a list:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1"></a><span class="op">&gt;&gt;&gt;</span> [x <span class="op">+</span> <span class="dv">4</span> <span class="cf">for</span> x <span class="kw">in</span> {<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>}]</span>
<span id="cb7-2"><a href="#cb7-2"></a>[<span class="dv">14</span>, <span class="dv">24</span>, <span class="dv">34</span>]</span>
<span id="cb7-3"><a href="#cb7-3"></a><span class="op">&gt;&gt;&gt;</span> [x <span class="op">*</span> <span class="dv">3</span> <span class="cf">for</span> x <span class="kw">in</span> [<span class="dv">100</span>, <span class="dv">200</span>, <span class="dv">300</span>]]</span>
<span id="cb7-4"><a href="#cb7-4"></a>[<span class="dv">300</span>, <span class="dv">600</span>, <span class="dv">900</span>]</span></code></pre></div>
<p>One word of warning: because sets are unordered but lists are ordered, you should <em>not</em> assume a particular ordering of the elements when a list comprehension generates elements from a set—the results can be unexpected!</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1"></a><span class="op">&gt;&gt;&gt;</span> [x <span class="cf">for</span> x <span class="kw">in</span> {<span class="dv">20</span>, <span class="dv">10</span>, <span class="dv">30</span>}]</span>
<span id="cb8-2"><a href="#cb8-2"></a>[<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>]</span></code></pre></div>
<p>A <strong>dictionary comprehension</strong> is again similar to a set comprehension, but specifies both an expression to generate keys and an expression to generate their associated values:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1"></a>{ <span class="op">&lt;</span>key_expr<span class="op">&gt;</span> : <span class="op">&lt;</span>value_expr<span class="op">&gt;</span> <span class="cf">for</span> <span class="op">&lt;</span>variable<span class="op">&gt;</span> <span class="kw">in</span> <span class="op">&lt;</span>collection<span class="op">&gt;</span> }</span></code></pre></div>
<p>Out of all three comprehension types, dictionary comprehensions are the most complex, because the left-hand side (before the <code>for</code>) consists of two expressions instead of one. Here is one example of a dictionary comprehension that creates a “table of values” for the function <span class="math inline">\(f(x) = x^2 + 1\)</span>.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1"></a><span class="op">&gt;&gt;&gt;</span> {x : x <span class="op">**</span> <span class="dv">2</span> <span class="op">+</span> <span class="dv">1</span> <span class="cf">for</span> x <span class="kw">in</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>}}</span>
<span id="cb10-2"><a href="#cb10-2"></a>{<span class="dv">1</span>: <span class="dv">2</span>, <span class="dv">2</span>: <span class="dv">5</span>, <span class="dv">3</span>: <span class="dv">10</span>, <span class="dv">4</span>: <span class="dv">17</span>, <span class="dv">5</span>: <span class="dv">26</span>}</span></code></pre></div>
<h2 id="comprehensions-with-multiple-variables">Comprehensions with multiple variables</h2>
<p>Our last example in this section will be to illustrate how multiple variables are used within the same comprehension expression. First, recall how we defined the <em>Cartesian product</em> of two sets using set builder notation: <span class="math display">\[ A \times B = \{ (x, y) \mid x \in A \text{ and } y \in B \}.\]</span> In this expression, the expression <span class="math inline">\((x, y)\)</span> is evaluated once for every possible combination of elements <span class="math inline">\(x\)</span> of <span class="math inline">\(A\)</span> and elements <span class="math inline">\(y\)</span> of <span class="math inline">\(B\)</span>.</p>
<p>The same holds for set, list, and dictionary comprehensions. We can specify additional variables in a comprehension by adding extra <code>for &lt;variable&gt; in &lt;collection&gt;</code> clauses to the comprehension. For example, if we define the following sets:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1"></a><span class="op">&gt;&gt;&gt;</span> nums1 <span class="op">=</span> {<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>}</span>
<span id="cb11-2"><a href="#cb11-2"></a><span class="op">&gt;&gt;&gt;</span> nums2 <span class="op">=</span> {<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>}</span></code></pre></div>
<p>then we can calculate their Cartesian product using the following set comprehension:<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote"> Remember, sets are unordered! Dont get hung up on the unusual order in the output.</span></p>
<div class="sourceCode" id="cb12"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1"></a><span class="op">&gt;&gt;&gt;</span> {(x, y) <span class="cf">for</span> x <span class="kw">in</span> nums1 <span class="cf">for</span> y <span class="kw">in</span> nums2}</span>
<span id="cb12-2"><a href="#cb12-2"></a>{(<span class="dv">3</span>, <span class="dv">30</span>), (<span class="dv">2</span>, <span class="dv">20</span>), (<span class="dv">2</span>, <span class="dv">10</span>), (<span class="dv">1</span>, <span class="dv">30</span>), (<span class="dv">3</span>, <span class="dv">20</span>), (<span class="dv">1</span>, <span class="dv">20</span>), (<span class="dv">3</span>, <span class="dv">10</span>), (<span class="dv">1</span>, <span class="dv">10</span>), (<span class="dv">2</span>, <span class="dv">30</span>)}</span></code></pre></div>
<p>In general, if we have a comprehension with clauses <code>for v1 in collection1</code>, <code>for v2 in collection2</code>, etc., then the comprehensions inner expression is evaluated <em>once for each combination of values for the variables</em>. This illustrates yet another pretty impressive power of Python: the ability to combine different collections of data together in a short amount of code.</p>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>
@@ -0,0 +1,213 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>1.6 Application: Representing Colour</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<link rel="stylesheet" href="../tufte.css" />
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" type="text/javascript"></script>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<div style="display:none">
\(
\newcommand{\NOT}{\neg}
\newcommand{\AND}{\wedge}
\newcommand{\OR}{\vee}
\newcommand{\XOR}{\oplus}
\newcommand{\IMP}{\Rightarrow}
\newcommand{\IFF}{\Leftrightarrow}
\newcommand{\TRUE}{\text{True}\xspace}
\newcommand{\FALSE}{\text{False}\xspace}
\newcommand{\IN}{\,{\in}\,}
\newcommand{\NOTIN}{\,{\notin}\,}
\newcommand{\TO}{\rightarrow}
\newcommand{\DIV}{\mid}
\newcommand{\NDIV}{\nmid}
\newcommand{\MOD}[1]{\pmod{#1}}
\newcommand{\MODS}[1]{\ (\text{mod}\ #1)}
\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\C}{\mathbb C}
\newcommand{\cA}{\mathcal A}
\newcommand{\cB}{\mathcal B}
\newcommand{\cC}{\mathcal C}
\newcommand{\cD}{\mathcal D}
\newcommand{\cE}{\mathcal E}
\newcommand{\cF}{\mathcal F}
\newcommand{\cG}{\mathcal G}
\newcommand{\cH}{\mathcal H}
\newcommand{\cI}{\mathcal I}
\newcommand{\cJ}{\mathcal J}
\newcommand{\cL}{\mathcal L}
\newcommand{\cK}{\mathcal K}
\newcommand{\cN}{\mathcal N}
\newcommand{\cO}{\mathcal O}
\newcommand{\cP}{\mathcal P}
\newcommand{\cQ}{\mathcal Q}
\newcommand{\cS}{\mathcal S}
\newcommand{\cT}{\mathcal T}
\newcommand{\cV}{\mathcal V}
\newcommand{\cW}{\mathcal W}
\newcommand{\cZ}{\mathcal Z}
\newcommand{\emp}{\emptyset}
\newcommand{\bs}{\backslash}
\newcommand{\floor}[1]{\left \lfloor #1 \right \rfloor}
\newcommand{\ceil}[1]{\left \lceil #1 \right \rceil}
\newcommand{\abs}[1]{\left | #1 \right |}
\newcommand{\xspace}{}
\newcommand{\proofheader}[1]{\underline{\textbf{#1}}}
\)
</div>
<header id="title-block-header">
<h1 class="title">1.6 Application: Representing Colour</h1>
</header>
<section>
<p>The physics behind how we perceive colour is incredibly interesting, but also complex. Humans have developed a broad range of names of colours to identify categories like “red” in everyday language.<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote"> Although the names we use for colours vary widely from language to language!</span> Yet these categories can be fairly broad and imprecise; useful for everyday communication, but not for computer graphics and design. So in this section, well learn about how computers represent colour data.</p>
<p><img src="https://images.unsplash.com/photo-1534872471805-7a1c5a014651?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=1052&amp;q=80" alt="color image" /><br />
</p>
<p>Mathematics can help us represent colours by a combination of numbers; the rules for how numbers map to colours is called a <em>colour model</em>. Many colour models exist, but one of the most common is the <em>RGB colour model</em>. At some point in your youth, you may have discovered that mixing two colours together (i.e., with paint, crayons, etc.) produces a different colour. The RGB colour model is based on the same idea: each colour is represented by three numbers, one for the “amount” of red, green, and blue to be mixed together.</p>
<p>A common form of the RGB colour model in a computer is called the <strong>RGB24</strong> colour model, and allows for each of the red, green, and blue amounts to be a number between 0 and 255, inclusive.<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote"> Though RGB24 is quite common, software like Photoshop allow for a larger range of numbers, enabling more granularity it their colour representations. You can look up the term <em>deep colour</em> to find out more about more sophisticated colour models</span> Formally, we can define the set <span class="math inline">\(S = \{0, 1, \dots, 255\}\)</span> and <span class="math inline">\(\mathcal{C}\)</span> to be the set of all possible colours in the universe. Then the RGB colour model is a function <span class="math inline">\(RGB_{24}: S \times S \times S \to \mathcal{C}\)</span> that takes in red, green, and blue values from <span class="math inline">\(S\)</span> and returns a colour. This <span class="math inline">\(RGB_{24}\)</span> function is <em>one-to-one</em>, as every combination of (red, green, blue) values produces a different colour.</p>
<table>
<colgroup>
<col style="width: 21%" />
<col style="width: 78%" />
</colgroup>
<thead>
<tr class="header">
<th>RGB Value</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>(0, 0, 0)</td>
<td><div height="10px" style="background-color: rgb(0,0,0)">
 
</div></td>
</tr>
<tr class="even">
<td>(255, 0, 0)</td>
<td><div height="10px" style="background-color: rgb(255,0,0)">
 
</div></td>
</tr>
<tr class="odd">
<td>(0, 255, 0)</td>
<td><div height="10px" style="background-color: rgb(0,255,0)">
 
</div></td>
</tr>
<tr class="even">
<td>(0, 0, 255)</td>
<td><div height="10px" style="background-color: rgb(0,0,255)">
 
</div></td>
</tr>
<tr class="odd">
<td>(181, 57, 173)</td>
<td><div height="10px" style="background-color: rgb(181,57,173)">
 
</div></td>
</tr>
<tr class="even">
<td>(255, 255, 255)</td>
<td><div height="10px" style="background-color: rgb(255,255,255)">
 
</div></td>
</tr>
</tbody>
</table>
<h3 id="colours-in-python">Colours in Python</h3>
<p>The RGB24 colour model translates naturally to Python: we represent a colour value as a tuple of three integers, where each integer is between 0 and 255, inclusive. For example, we can use <code>(0, 0, 0)</code> to represent a pure black, and <code>(181, 57, 173)</code> to represent a shade of purple. Of course, just representing these values as tuples doesnt automatically make them colours:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1"></a><span class="op">&gt;&gt;&gt;</span> (<span class="dv">181</span>, <span class="dv">57</span>, <span class="dv">173</span>) <span class="co"># This tuple evaluates to... itself</span></span>
<span id="cb1-2"><a href="#cb1-2"></a>(<span class="dv">181</span>, <span class="dv">57</span>, <span class="dv">173</span>)</span></code></pre></div>
<p>But as youll see in your first tutorial this year, we can pass these tuples to operations that expect colour values, and get remarkable results.</p>
<p><img src="images/colour_gradient.png" alt="Pygame demo of colour gradient" /><br />
</p>
<h2 id="references">References</h2>
<ul>
<li><a href="https://www.mathsisfun.com/hexadecimal-decimal-colors.html">Hexadecimal Colors</a></li>
<li><a href="http://learn.colorotate.org/color-models/">Color Theory</a></li>
</ul>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>