index.html 20 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="last-modified" content="2017-08-04 00:20:27 +0200">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- meta "search-domain" used for google site search function google_search() -->
    <meta name="search-domain" value="/swc-releases/2017.08/python-novice-inflammation">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/lesson.css" />
    
    <link rel="shortcut icon" type="image/x-icon" href="/favicon-swc.ico" />
    
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
	<![endif]-->
    <title>Programming with Python: Discussion</title>
  </head>
  <body>
    <div class="container">
      
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>

      
      

      
      <a class="navbar-brand" href="../">Home</a>

    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">

	
        <li><a href="../conduct/">Code of Conduct</a></li>

	
        
        <li><a href="../setup/">Setup</a></li>
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Episodes <span class="caret"></span></a>
          <ul class="dropdown-menu">
            
            <li><a href="../01-numpy/">Analyzing Patient Data</a></li>
            
            <li><a href="../02-loop/">Repeating Actions with Loops</a></li>
            
            <li><a href="../03-lists/">Storing Multiple Values in Lists</a></li>
            
            <li><a href="../04-files/">Analyzing Data from Multiple Files</a></li>
            
            <li><a href="../05-cond/">Making Choices</a></li>
            
            <li><a href="../06-func/">Creating Functions</a></li>
            
            <li><a href="../07-errors/">Errors and Exceptions</a></li>
            
            <li><a href="../08-defensive/">Defensive Programming</a></li>
            
            <li><a href="../09-debugging/">Debugging</a></li>
            
            <li><a href="../10-cmdline/">Command-Line Programs</a></li>
            
	    <li role="separator" class="divider"></li>
            <li><a href="../aio/">All in one page (Beta)</a></li>
          </ul>
        </li>
	

	
	
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Extras <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="../reference/">Reference</a></li>
            
            <li><a href="../about/">About</a></li>
            
            <li><a href="../discuss/">Discussion</a></li>
            
            <li><a href="../figures/">Figures</a></li>
            
            <li><a href="../guide/">Instructor Notes</a></li>
            
          </ul>
        </li>
	

	
        <li><a href="../license/">License</a></li>
	
	<li><a href="/edit/gh-pages/_extras/discuss.md">Improve this page <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a></li>
	
      </ul>
      <form class="navbar-form navbar-right" role="search" id="search" onsubmit="google_search(); return false;">
        <div class="form-group">
          <input type="text" id="google-search" placeholder="Search..." aria-label="Google site search">
        </div>
      </form>
    </div>
  </div>
</nav>


<h1 class="maintitle"><a href="../">Programming with Python</a>: Discussion</h1>

<h2 id="rules-of-debugging">Rules of Debugging</h2>

<ol>
  <li>Fail early, fail often.</li>
  <li>Always initialize from data.</li>
  <li>Know what it’s supposed to do.</li>
  <li>Make it fail every time.</li>
  <li>Make it fail fast.</li>
  <li>Change one thing at a time, for a reason.</li>
  <li>Keep track of what we’ve done.</li>
  <li>Be humble.</li>
  <li>Test the simple things first.</li>
</ol>

<p>And remember,
a week of hard work can sometimes save you an hour of thought.</p>

<h2 id="the-call-stack">The Call Stack</h2>

<p>Let’s take a closer look at what happens when we call <code class="highlighter-rouge">fahr_to_celsius(32.0)</code>.
To make things clearer,
we’ll start by putting the initial value 32.0 in a variable
and store the final result in one as well:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>original = 32.0
final = fahr_to_celsius(original)
</code></pre>
</div>

<p>The diagram below shows what memory looks like after the first line has been executed:</p>

<p><img src="../fig/python-call-stack-01.svg" alt="Call Stack (Initial State)" /></p>

<p>When we call <code class="highlighter-rouge">fahr_to_celsius</code>,
Python <em>doesn’t</em> create the variable <code class="highlighter-rouge">temp</code> right away.
Instead,
it creates something called a <a href="../reference/#stack-frame">stack frame</a>
to keep track of the variables defined by <code class="highlighter-rouge">fahr_to_kelvin</code>.
Initially,
this stack frame only holds the value of <code class="highlighter-rouge">temp</code>:</p>

<p><img src="../fig/python-call-stack-02.svg" alt="Call Stack Immediately After First Function Call" /></p>

<p>When we call <code class="highlighter-rouge">fahr_to_kelvin</code> inside <code class="highlighter-rouge">fahr_to_celsius</code>,
Python creates another stack frame to hold <code class="highlighter-rouge">fahr_to_kelvin</code>’s variables:</p>

<p><img src="../fig/python-call-stack-03.svg" alt="Call Stack During First Nested Function Call" /></p>

<p>It does this because there are now two variables in play called <code class="highlighter-rouge">temp</code>:
the parameter to <code class="highlighter-rouge">fahr_to_celsius</code>,
and the parameter to <code class="highlighter-rouge">fahr_to_kelvin</code>.
Having two variables with the same name in the same part of the program would be ambiguous,
so Python (and every other modern programming language) creates a new stack frame for each function call
to keep that function’s variables separate from those defined by other functions.</p>

<p>When the call to <code class="highlighter-rouge">fahr_to_kelvin</code> returns a value,
Python throws away <code class="highlighter-rouge">fahr_to_kelvin</code>’s stack frame
and creates a new variable in the stack frame for <code class="highlighter-rouge">fahr_to_celsius</code> to hold the temperature in Kelvin:</p>

<p><img src="../fig/python-call-stack-04.svg" alt="Call Stack After Return From First Nested Function Call" /></p>

<p>It then calls <code class="highlighter-rouge">kelvin_to_celsius</code>,
which means it creates a stack frame to hold that function’s variables:</p>

<p><img src="../fig/python-call-stack-05.svg" alt="Call Stack During Call to Second Nested Function" /></p>

<p>Once again,
Python throws away that stack frame when <code class="highlighter-rouge">kelvin_to_celsius</code> is done
and creates the variable <code class="highlighter-rouge">result</code> in the stack frame for <code class="highlighter-rouge">fahr_to_celsius</code>:</p>

<p><img src="../fig/python-call-stack-06.svg" alt="Call Stack After Second Nested Function Returns" /></p>

<p>Finally,
when <code class="highlighter-rouge">fahr_to_celsius</code> is done,
Python throws away <em>its</em> stack frame
and puts its result in a new variable called <code class="highlighter-rouge">final</code>
that lives in the stack frame we started with:</p>

<p><img src="../fig/python-call-stack-07.svg" alt="Call Stack After All Functions Have Finished" /></p>

<p>This final stack frame is always there;
it holds the variables we defined outside the functions in our code.
What it <em>doesn’t</em> hold is the variables that were in the various stack frames.
If we try to get the value of <code class="highlighter-rouge">temp</code> after our functions have finished running,
Python tells us that there’s no such thing:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('final value of temp after all function calls:', temp)
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
&lt;ipython-input-12-ffd9b4dbd5f1&gt; in &lt;module&gt;()
----&gt; 1 print('final value of temp after all function calls:', temp)

NameError: name 'temp' is not defined
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>final value of temp after all function calls:
</code></pre>
</div>

<p>Why go to all this trouble?
Well,
here’s a function called <code class="highlighter-rouge">span</code> that calculates the difference between
the minimum and maximum values in an array:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>import numpy

def span(a):
    diff = numpy.max(a) - numpy.min(a)
    return diff

data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')
print('span of data:', span(data))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>span of data: 20.0
</code></pre>
</div>

<p>Notice that <code class="highlighter-rouge">span</code> assigns a value to a variable called <code class="highlighter-rouge">diff</code>.
We might very well use a variable with the same name to hold data:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code><span class="gh">diff = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')
</span>print('span of data:', span(diff))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>span of data: 20.0
</code></pre>
</div>

<p>We don’t expect <code class="highlighter-rouge">diff</code> to have the value 20.0 after this function call,
so the name <code class="highlighter-rouge">diff</code> cannot refer to the same thing inside <code class="highlighter-rouge">span</code> as it does in the main body of our program.
And yes,
we could probably choose a different name than <code class="highlighter-rouge">diff</code> in our main program in this case,
but we don’t want to have to read every line of NumPy to see what variable names its functions use
before calling any of those functions,
just in case they change the values of our variables.</p>

<p>The big idea here is <a href="../reference/#encapsulation">encapsulation</a>,
and it’s the key to writing correct, comprehensible programs.
A function’s job is to turn several operations into one
so that we can think about a single function call
instead of a dozen or a hundred statements
each time we want to do something.
That only works if functions don’t interfere with each other;
if they do,
we have to pay attention to the details once again,
which quickly overloads our short-term memory.</p>

<blockquote class="challenge">
  <h2 id="following-the-call-stack">Following the Call Stack</h2>

  <p>We previously wrote functions called <code class="highlighter-rouge">fence</code> and <code class="highlighter-rouge">outer</code>.
Draw a diagram showing how the call stack changes when we run the following:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>print(outer(fence('carbon', '+')))
</code></pre>
  </div>
</blockquote>

<h2 id="image-grids">Image Grids</h2>

<p>Let’s start by creating some simple heat maps of our own
using a library called <code class="highlighter-rouge">ipythonblocks</code>.
The first step is to create our own “image”:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>from ipythonblocks import ImageGrid
</code></pre>
</div>

<p>Unlike the <code class="highlighter-rouge">import</code> statements we have seen earlier,
this one doesn’t load the entire <code class="highlighter-rouge">ipythonblocks</code> library.
Instead,
it just loads <code class="highlighter-rouge">ImageGrid</code> from that library,
since that’s the only thing we need (for now).</p>

<p>Once we have <code class="highlighter-rouge">ImageGrid</code> loaded,
we can use it to create a very simple grid of colored cells:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>grid = ImageGrid(5, 3)
grid.show()
</code></pre>
</div>

<p><img src="../fig/grid-01.png" alt="" /></p>

<p>Just like a NumPy array,
an <code class="highlighter-rouge">ImageGrid</code> has some properties that hold information about it:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('grid width:', grid.width)
print('grid height:', grid.height)
print('grid lines on:', grid.lines_on)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>grid width: 5
grid height: 3
grid lines on: True
</code></pre>
</div>

<p>The obvious thing to do with a grid like this is color in its cells,
but in order to do that,
we need to know how computers represent color.
The most common schemes are <a href="../reference/#rgb">RGB</a>,
which is short for “red, green, blue”.
RGB is an <a href="../reference/#additive-color-model">additive color model</a>:
every shade is some combination of red, green, and blue intensities.
We can think of these three values as being the axes in a cube:</p>

<p><img src="../fig/color-cube.png" alt="RGB Color Cube" /></p>

<p>An RGB color is an example of a multi-part value:
like a Cartesian coordinate,
it is one thing with several parts.
We can represent such a value in Python using a <a href="../reference/#tuple">tuple</a>,
which we write using parentheses instead of the square brackets used for a list:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>position = (12.3, 45.6)
print('position is:', position)
color = (10, 20, 30)
print('color is:', color)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>position is: (12.3, 45.6)
color is: (10, 20, 30)
</code></pre>
</div>

<p>We can select elements from tuples using indexing,
just as we do with lists and arrays:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('first element of color is:', color[0])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>first element of color is: 10
</code></pre>
</div>

<p>Unlike lists and arrays,
though,
tuples cannot be changed after they are created — in technical terms,
they are <a href="../reference/#immutable">immutable</a>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>color[0] = 40
print('first element of color after change:', color[0])
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-11-9c3dd30a4e52&gt; in &lt;module&gt;()
----&gt; 1 color[0] = 40
2 print('first element of color after change:', color[0])

TypeError: 'tuple' object does not support item assignment
</code></pre>
</div>

<p>If a tuple represents an RGB color,
its red, green, and blue components can take on values between 0 and 255.
The upper bound may seem odd,
but it’s the largest number that can be represented in an 8-bit byte
(i.e., 2<sup>8</sup>-1).
This makes it easy for computers to manipulate colors,
while providing fine enough gradations to fool most human eyes,
most of the time.</p>

<p>Let’s see what a few RGB colors actually look like:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>row = ImageGrid(8, 1)
row[0, 0] = (0, 0, 0)   # no color =&gt; black
row[1, 0] = (255, 255, 255) # all colors =&gt; white
row[2, 0] = (255, 0, 0) # all red
row[3, 0] = (0, 255, 0) # all green
row[4, 0] = (0, 0, 255) # all blue
row[5, 0] = (255, 255, 0) # red and green
row[6, 0] = (255, 0, 255) # red and blue
row[7, 0] = (0, 255, 255) # green and blue
row.show()
</code></pre>
</div>

<p><img src="../fig/grid-02.png" alt="" /></p>

<p>Simple color values like <code class="highlighter-rouge">(0,255,0)</code> are easy enough to decipher with a bit of practice,
but what color is <code class="highlighter-rouge">(214,90,127)</code>?
To help us,
<code class="highlighter-rouge">ipythonblocks</code> provides a function called <code class="highlighter-rouge">show_color</code>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>from ipythonblocks import show_color
show_color(214, 90, 127)
</code></pre>
</div>

<p><img src="../fig/ipythonblocks_show_color_example.png" alt="" /></p>

<p>It also provides a table of standard colors:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>from ipythonblocks import colors
c = ImageGrid(3, 2)
c[0, 0] = colors['Fuchsia']
c[0, 1] = colors['Salmon']
c[1, 0] = colors['Orchid']
c[1, 1] = colors['Lavender']
c[2, 0] = colors['LimeGreen']
c[2, 1] = colors['HotPink']
c.show()
</code></pre>
</div>

<p><img src="../fig/grid-03.png" alt="" /></p>

<blockquote class="challenge">
  <h2 id="making-a-colorbar">Making a Colorbar</h2>

  <p>Fill in the <code class="highlighter-rouge">____</code> in the code below to create a bar that changes color from dark blue to black.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>bar = ImageGrid(10, 1)
for x in range(10):
    bar[x, 0] = (0, 0, ____)
bar.show()
</code></pre>
  </div>
</blockquote>

<blockquote class="challenge">
  <h2 id="why-rgb">Why RGB?</h2>

  <p>Why do computers use red, green, and blue as their primary colors?</p>
</blockquote>

<blockquote class="challenge">
  <h2 id="nested-loops">Nested Loops</h2>

  <p>Will changing the nesting of the loops in the code above — i.e.,
wrapping the Y-axis loop around the X-axis loop — change the final image?
Why or why not?</p>
</blockquote>

<blockquote class="challenge">
  <h2 id="where-to-change-data">Where to Change Data</h2>

  <p>Why did we transpose our data outside our heat map function?
Why not have the function perform the transpose?</p>
</blockquote>

<blockquote class="challenge">
  <h2 id="return-versus-display">Return Versus Display</h2>

  <p>Why does the heat map function return the grid rather than displaying it immediately?
Do you think this is a good or bad design choice?</p>
</blockquote>


      
      
<footer>
  <div class="row">
    <div class="col-md-6" align="left">
      <h4>
	Copyright &copy; 2016–2017
	
	<a href="https://software-carpentry.org">Software Carpentry Foundation</a>
	
      </h4>
    </div>
    <div class="col-md-6" align="right">
      <h4>
	
	<a href="/edit/gh-pages/_extras/discuss.md">Edit on GitHub</a>
	
	/
	<a href="/blob/gh-pages/CONTRIBUTING.md">Contributing</a>
	/
	<a href="/">Source</a>
	/
	<a href="/blob/gh-pages/CITATION">Cite</a>
	/
	<a href="">Contact</a>
      </h4>
    </div>
  </div>
</footer>

      
    </div>
    
<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/lesson.js"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-37305346-2', 'auto');
  ga('send', 'pageview');
</script>

  </body>
</html>