Files
CSC110/02-functions/07-type-conversions.html
Hykilpikonna 6fffdf686a deploy
2021-12-07 22:28:01 -05:00

207 lines
17 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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>2.7 Type Conversion Functions</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" />
<!--[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">2.7 Type Conversion Functions</h1>
</header>
<section>
<p>There is another useful set of built-in functions that we have not yet discussed: functions that allow us to convert values between different data types. For example, given a string <code>'10'</code>, can we convert it into the integer <code>10</code>? Or given a list <code>[1, 2, 3]</code>, can we convert it into a set <code>{1, 2, 3}</code>?</p>
<p>The answer to these questions is yes, and the way to do so in Python is quite elegant. Each data type that we have learned about so far, from <code>int</code> to <code>dict</code>, is also a function that takes an argument and attempts to convert it to a value of that data type.</p>
<p>Here are some examples:<label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle"/><span class="sidenote"> Some of these are more “obvious” than others. Dont worry about the exact rules for conversions between types, as you wont be expected to memorize them. Instead, we just want you to know that these conversions are possible using data types as functions.</span></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="bu">int</span>(<span class="st">&#39;10&#39;</span>)</span>
<span id="cb1-2"><a href="#cb1-2"></a><span class="dv">10</span></span>
<span id="cb1-3"><a href="#cb1-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">float</span>(<span class="st">&#39;10&#39;</span>)</span>
<span id="cb1-4"><a href="#cb1-4"></a><span class="fl">10.0</span></span>
<span id="cb1-5"><a href="#cb1-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">bool</span>(<span class="dv">1000</span>)</span>
<span id="cb1-6"><a href="#cb1-6"></a><span class="va">True</span></span>
<span id="cb1-7"><a href="#cb1-7"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">bool</span>(<span class="dv">0</span>)</span>
<span id="cb1-8"><a href="#cb1-8"></a><span class="va">False</span></span>
<span id="cb1-9"><a href="#cb1-9"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">list</span>({<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>})</span>
<span id="cb1-10"><a href="#cb1-10"></a>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]</span>
<span id="cb1-11"><a href="#cb1-11"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">set</span>([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>])</span>
<span id="cb1-12"><a href="#cb1-12"></a>{<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>}</span>
<span id="cb1-13"><a href="#cb1-13"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">set</span>() <span class="co"># Giving set no arguments results in the empty set</span></span>
<span id="cb1-14"><a href="#cb1-14"></a><span class="bu">set</span>()</span>
<span id="cb1-15"><a href="#cb1-15"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">dict</span>([(<span class="st">&#39;a&#39;</span>, <span class="dv">1</span>), (<span class="st">&#39;b&#39;</span>, <span class="dv">2</span>), (<span class="st">&#39;c&#39;</span>, <span class="dv">3</span>)])</span>
<span id="cb1-16"><a href="#cb1-16"></a>{<span class="st">&#39;a&#39;</span>: <span class="dv">1</span>, <span class="st">&#39;b&#39;</span>: <span class="dv">2</span>, <span class="st">&#39;c&#39;</span>: <span class="dv">3</span>}</span></code></pre></div>
<p>In particular, <code>str</code> is the most versatile of these data types. <em>Every</em> value of the data types weve studied so far has a string represention which corresponds directly to how you would write the value as a Python literal.</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="bu">str</span>(<span class="dv">10</span>)</span>
<span id="cb2-2"><a href="#cb2-2"></a><span class="co">&#39;10&#39;</span></span>
<span id="cb2-3"><a href="#cb2-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">str</span>(<span class="op">-</span><span class="fl">5.5</span>)</span>
<span id="cb2-4"><a href="#cb2-4"></a><span class="co">&#39;-5.5&#39;</span></span>
<span id="cb2-5"><a href="#cb2-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">str</span>(<span class="va">True</span>)</span>
<span id="cb2-6"><a href="#cb2-6"></a><span class="co">&#39;True&#39;</span></span>
<span id="cb2-7"><a href="#cb2-7"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">str</span>({<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>})</span>
<span id="cb2-8"><a href="#cb2-8"></a><span class="co">&#39;{1, 2, 3}&#39;</span></span>
<span id="cb2-9"><a href="#cb2-9"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">str</span>([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>])</span>
<span id="cb2-10"><a href="#cb2-10"></a><span class="co">&#39;[1, 2, 3]&#39;</span></span>
<span id="cb2-11"><a href="#cb2-11"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">str</span>({<span class="st">&#39;a&#39;</span>: <span class="dv">1</span>, <span class="st">&#39;b&#39;</span>: <span class="dv">2</span>})</span>
<span id="cb2-12"><a href="#cb2-12"></a><span class="co">&quot;{&#39;a&#39;: 1, &#39;b&#39;: 2}&quot;</span></span></code></pre></div>
<h2 id="warning-conversion-errors">Warning: conversion errors</h2>
<p>You often have to be careful when attempting to convert between different data types, as not all values of one type can be converted into another. Attempting to convert an “invalid” value often results in a Python exception to be raised:<label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle"/><span class="sidenote"> These exceptions typically have type <code>ValueError</code> or <code>TypeError</code>.</span></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="bu">int</span>(<span class="st">&#39;David&#39;</span>)</span>
<span id="cb3-2"><a href="#cb3-2"></a>Traceback (most recent call last):</span>
<span id="cb3-3"><a href="#cb3-3"></a> File <span class="st">&quot;&lt;stdin&gt;&quot;</span>, line <span class="dv">1</span>, <span class="kw">in</span> <span class="op">&lt;</span>module<span class="op">&gt;</span></span>
<span id="cb3-4"><a href="#cb3-4"></a><span class="pp">ValueError</span>: invalid literal <span class="cf">for</span> <span class="bu">int</span>() <span class="cf">with</span> base <span class="dv">10</span>: <span class="st">&#39;David&#39;</span></span>
<span id="cb3-5"><a href="#cb3-5"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">list</span>(<span class="dv">1000</span>)</span>
<span id="cb3-6"><a href="#cb3-6"></a>Traceback (most recent call last):</span>
<span id="cb3-7"><a href="#cb3-7"></a> File <span class="st">&quot;&lt;stdin&gt;&quot;</span>, line <span class="dv">1</span>, <span class="kw">in</span> <span class="op">&lt;</span>module<span class="op">&gt;</span></span>
<span id="cb3-8"><a href="#cb3-8"></a><span class="pp">TypeError</span>: <span class="st">&#39;int&#39;</span> <span class="bu">object</span> <span class="kw">is</span> <span class="kw">not</span> iterable</span></code></pre></div>
<h2 id="preview-creating-values-of-arbitrary-data-types">Preview: creating values of arbitrary data types</h2>
<p>The ability to create values of a given type by calling the data type as a function is not unique to the built-in data types in this section. Weve actually seen two examples of doing this so far in the course!</p>
<h3 id="range-revisited"><code>range</code> revisited</h3>
<p>Earlier, we saw that we could call <code>range</code> to create a sequence of numbers. But if you just try calling <code>range</code> by itself in the Python console, you see something kind of funny:</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="bu">range</span>(<span class="dv">5</span>, <span class="dv">10</span>)</span>
<span id="cb4-2"><a href="#cb4-2"></a><span class="bu">range</span>(<span class="dv">5</span>, <span class="dv">10</span>)</span></code></pre></div>
<p>Whereas you might have expected to see a list (<code>[5, 6, 7, 8, 9]</code>), in the Python console output it looks like nothing happened at all! This is because <code>range</code> is actually a type conversion function: Python also has a <code>range</code> data type that is distinct from lists (or other collection data types).</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> five_to_nine <span class="op">=</span> <span class="bu">range</span>(<span class="dv">5</span>, <span class="dv">10</span>)</span>
<span id="cb5-2"><a href="#cb5-2"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">type</span>(five_to_nine)</span>
<span id="cb5-3"><a href="#cb5-3"></a><span class="op">&lt;</span><span class="kw">class</span> <span class="st">&#39;range&#39;</span><span class="op">&gt;</span></span>
<span id="cb5-4"><a href="#cb5-4"></a><span class="op">&gt;&gt;&gt;</span> five_to_nine <span class="op">==</span> [<span class="dv">5</span>, <span class="dv">6</span>, <span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>]</span>
<span id="cb5-5"><a href="#cb5-5"></a><span class="va">False</span></span></code></pre></div>
<h3 id="datetime.date-revisited"><code>datetime.date</code> revisited</h3>
<p>Recall an example from the last section in <a href="04-importing-modules.html">Section 2.4 Importing Modules</a>:</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="im">import</span> datetime</span>
<span id="cb6-2"><a href="#cb6-2"></a><span class="op">&gt;&gt;&gt;</span> canada_day <span class="op">=</span> datetime.date(<span class="dv">1867</span>, <span class="dv">7</span>, <span class="dv">1</span>) <span class="co"># Create a new date</span></span>
<span id="cb6-3"><a href="#cb6-3"></a><span class="op">&gt;&gt;&gt;</span> <span class="bu">type</span>(canada_day)</span>
<span id="cb6-4"><a href="#cb6-4"></a><span class="op">&lt;</span><span class="kw">class</span> <span class="st">&#39;datetime.date&#39;</span><span class="op">&gt;</span></span></code></pre></div>
<p>In this case, the data type is <code>datetime.date</code>, and it is called on three arguments instead of one. In this context, <code>datetime.date</code> is called to <em>create</em> a new <code>date</code> value given three arguments (the year, month, and day).<label for="sn-2" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-2" class="margin-toggle"/><span class="sidenote"> This is a more general form of type “conversion”, which created a data type of a new value given a single argument.</span> And of course, this behaviour isnt unique to <code>datetime.date</code> either. As well see a bit later in this course, youll be able to take <em>any</em> data type—even ones you define yourself—and create values of that type by calling the data type as a function.</p>
</section>
<footer>
<a href="https://www.teach.cs.toronto.edu/~csc110y/fall/notes/">CSC110 Course Notes Home</a>
</footer>
</body>
</html>