<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Python Tutorials for Kids 8+</title>
	<atom:link href="http://python4kids.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://python4kids.wordpress.com</link>
	<description>Let&#039;s learn Python!</description>
	<lastBuildDate>Sat, 17 Dec 2011 13:42:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='python4kids.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Python Tutorials for Kids 8+</title>
		<link>http://python4kids.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://python4kids.wordpress.com/osd.xml" title="Python Tutorials for Kids 8+" />
	<atom:link rel='hub' href='http://python4kids.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Interlude &#8211; Comments on Learning and Debugging</title>
		<link>http://python4kids.wordpress.com/2011/12/05/interlude-comments-on-learning-and-debugging/</link>
		<comments>http://python4kids.wordpress.com/2011/12/05/interlude-comments-on-learning-and-debugging/#comments</comments>
		<pubDate>Mon, 05 Dec 2011 12:58:12 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=371</guid>
		<description><![CDATA[Hello. Hello people, and welcome to &#8216;It&#8217;s a Tree&#8217;. We have some really exiting guests for you this evening. A fabulous spruce, back from a tour of Holland, three gum trees making their first appearance in this country, scots pine and the conifers, and Elm Tree Bole &#8211; there you go, can&#8217;t be bad &#8211; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=371&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode10.htm#4">Hello. Hello people, and welcome to &#8216;It&#8217;s a Tree&#8217;. We have some really exiting guests for you this evening. A fabulous spruce, back from a tour of Holland, three gum trees making their first appearance in this country, scots pine and the conifers, and Elm Tree Bole &#8211; there you go, can&#8217;t be bad &#8211; an exiting new American plank, a rainforest and a bucket of sawdust giving their views on teenage violence, and an unusual guest for this programme, a piece of laminated plastic.</a></p>
<p>No tutes for while now &#8211; this part of the year gets very busy, so I&#8217;m sorry that we haven&#8217;t been having updates.  Part of the reason was that I was working on a short project (lunar lander) to use as an example here, but it seems to have run out of control with too much complexity &#8211; so I probably won&#8217;t be using it &#8211; or I will have to pare it back a fair bit.  Tutes will probably be sparse until after Christmas.</p>
<p><a href="http://python4kids.wordpress.com/2011/06/02/making-this-code-your-own/">In an earlier tutorial</a> I talked about how to make the code here your own.  I wanted to expand on those comments a little here.  First, the best way to learn is by doing.  When you simply listen or read something you don&#8217;t actually understand what is involved.  This is because when you listen only you will not understand the complexities or interactions that are going on.  Nor will you be making mistakes, because you&#8217;re not doing anything.  When I was working on the lunar lander I realised how many mistakes I was making when coding &#8211; and they were mistakes you will never see so ones you won&#8217;t learn from.</p>
<p>A <a href="http://en.wikipedia.org/wiki/Corollary">corollary</a> of the first principle is that you should be doing the homework I set.  When you do the homework you should keep in mind that I expect that you will be able to work it out based on the tutorial itself &#8211; or, in some cases, using earlier tutorials. So keep in mind that the homework is not super hard (those  parts marked &#8220;extra points&#8221; may well be too hard).  It is doable.  Revisit the tutorial itself and see what bits of it seem relevant.  Then try to think how you can apply those bits.  Never start from the position that you need to know some extra, mystical piece of knowledge other than what has been covered already &#8211; and in the vast majority of cases, other than what is covered in that specific tutorial.  If you really can&#8217;t work it out, post a comment.</p>
<p>Try and try again! No one gets everything right on the first try.  While Python syntax is not difficult, it can still take some time to master. You need to go through the pain of getting it wrong in order to learn how it works.  Sooner or later it will become second nature.  The pain of working it out the first time will pay off.</p>
<p>When working on your own project, think big, but start little.  Try to map out what will be involved, so far as you can.  If you can&#8217;t foresee each step, that&#8217;s not a problem, it will come to you.  Implement the part of the project that you feel confident doing, and then expand it from there.  It is often the case that the intial work on getting something going is much harder than improving it later. This might be because with new projects there is a period in which you can&#8217;t even run the code to show results. In this period you are working only on your faith in your own ability.  However, once you get the initial work done and can see something to show for your effort, expanding on that work is much easier, and more satisfying because a comparatively small amount of work can produce a substantially different result.  You will find that you will need to &#8220;refactor&#8221; the code (that is rewrite it, usually restructuring it) from time to time.  The amount by which you need to refactor will be dependent on what you knew and how much you planned before you started.  Refactoring is, by and large, unavoidable.</p>
<p>Use Python&#8217;s help() introspection to get help about a function.  When you are using a function or a method, make sure that the arguments you pass to the method are the same as the function is expecting and also that they are in the same order as the function is expecting.   Where I give a solution to a problem, try to understand why they solution works.</p>
<p>Adopt code that does some of what you want and expand from it, making changes here and there.  This, of course, depends on there being such code to adopt and your being able to find it.  If you are able to do this it is a good way to learn.  For example, if you look on the web, you&#8217;ll find a space invaders type tutorial.  Extending it means you can focus on just the extension, with the rest having been done for you.  You can, nevertheless, improve on it one piece at a time and get some gratification from achieving those things.</p>
<p>Look at my tute on <a href="http://python4kids.wordpress.com/2011/06/25/talk-to-your-teddy-debugging/">debugging</a>.  When you get something wrong, look at the message that Python gives you.  These messages can be cryptic, but they do have information in them that you can extract if you&#8217;re careful. Also, carefully compare what you have done to the code in the tute.</p>
<p>Finally, and most importantly: trust in yourself.  I am confident you are able to do this work. All you need is to commit to getting it done.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/371/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=371&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/12/05/interlude-comments-on-learning-and-debugging/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Classy Methods, a Sense of Self (Classes Part 2)</title>
		<link>http://python4kids.wordpress.com/2011/10/17/classy-methods-a-sense-of-self-classes-part-2/</link>
		<comments>http://python4kids.wordpress.com/2011/10/17/classy-methods-a-sense-of-self-classes-part-2/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 02:33:18 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=362</guid>
		<description><![CDATA[Ratcatcher     Hello &#8211; Mr and Mrs Concrete? Both     Yes. Ratcatcher     Well, well, well, well, well, well, well, well, well, well, well, how very nice. Allow me to introduce myself. I am Leslie Ames, the Chairman of the Test Selection Committee, and I&#8217;m very pleased to be able to tell you that your [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=362&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.ibras.dk/montypython/episode20.htm#5">Ratcatcher     Hello &#8211; Mr and Mrs Concrete?<br />
Both     Yes.<br />
Ratcatcher     Well, well, well, well, well, well, well, well, well, well, well, how very nice. Allow me to introduce myself. I am Leslie Ames, the Chairman of the Test Selection Committee, and I&#8217;m very pleased to be able to tell you that your flat has been chosen as the venue for the third test against the West Indies.<br />
Mrs Concrete     Really?<br />
Ratcatcher     No, it was just a little joke. Actually, I am the Council Ratcatcher.</a></em></p>
<p>In our last tutorial we had our first look at <em>classes</em> and their <em>attributes. </em> The <em>attributes</em> of a class are the data which are stored in the <em>class.  </em> The great thing about <em>classes</em> though is that we can use them to relate data to <em>functions. </em> Just as the data of a <em>class</em> are called <em>attributes,</em> the <em>functions</em> of a <em>class</em> have a special name as well.  They are called &#8220;methods&#8221;. We have had a brief meeting with <em>methods</em> <a href="http://python4kids.wordpress.com/2011/03/07/time-for-some-introspection/">earlier</a>.</p>
<p>Let&#8217;s (re)create the <em>class</em> from the <a href="http://python4kids.wordpress.com/2011/09/26/classy-attributes/">previous tutorial</a>:</p>
<pre>&gt;&gt;&gt; class allDads(object):
 ...    pass
 ...</pre>
<p>Now, let&#8217;s add a <em>method</em> to it:</p>
<pre>&gt;&gt;&gt; allDads.r = range
&gt;&gt;&gt; allDads.r(6)
 [0, 1, 2, 3, 4, 5]
</pre>
<p>Here we&#8217;ve added Python&#8217;s &#8220;built in&#8221; <em>range()</em> function to the <em>allDads</em> <em>class. </em> Just as with <em>attributes,</em> when you create an instance of a class, the <em>methods</em> of the <em>class</em> are also <em>inherited</em> by the <em>instance:</em></p>
<pre>&gt;&gt;&gt; myDad = allDads()
 &gt;&gt;&gt; myDad.r(6)
 [0, 1, 2, 3, 4, 5]</pre>
<p>Changing an <em>instance&#8217;s</em> <em>method</em> does not change the <em>class&#8217;s method</em>:</p>
<pre>&gt;&gt;&gt; myDad.r = repr
&gt;&gt;&gt; myDad.r(6)                                                                                                                                                           '6'</pre>
<p>So, we have replaced the <em>r</em> <em>function</em> for the <em>instance</em> <em>myDad</em> of the <em>class allDads</em> with Python&#8217;s &#8220;built in&#8221; <em><a href="http://docs.python.org/library/functions.html#repr">repr</a></em> <em>function.  </em> We have briefly met <em>repr</em> before &#8211; what it does is (tries to) convert the object passed to it to a <em>string</em> so that you can print it.  You can see in this example that the number 6 has been converted into the <em>string</em> &#8217;6&#8242; (note the inverted commas).</p>
<p>Just for good measure, I&#8217;ll show that defining the method r doesn&#8217;t create a function of the same name:</p>
<pre>&gt;&gt;&gt; r(6)                                                                                                                                                                 
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'r' is not defined</pre>
<p><strong>Overriding </strong></p>
<p>You might not have noticed it, but we just covered one of the most powerful, mind blowing aspects of classes.   It&#8217;s called &#8220;overriding&#8221;.  Overriding occurs where an object which inherits from a class assigns a different method to the method the class has.  We will return to overriding a little later, but make a note for now that it&#8217;s important.  We don&#8217;t talk about overriding attributes, probably (I don&#8217;t actually know) because with attributes you&#8217;re just changing a value rather than substituting programming code which will be executed.</p>
<p>The <em>r</em> method of <em>allDads</em> is a bit silly.  The <em>range</em> <em>method</em> doesn&#8217;t have any meaning for <em>allDads</em> &#8211; nor, for that matter, does <em>repr. </em> You would not normally add <em>methods</em> to a <em>class</em> after it has been defined.  It would be more normal to have all of the <em>class&#8217;s methods</em> set out as part of the definition of the <em>class</em> itself.</p>
<p><strong>Init and a sense of self</strong></p>
<p>There is a special method for classes (called __init__ [1]) which seems like it is silly (how do you <em>__init__</em> a dad?), but it turns out to be very important.  The <em>__init__</em> method initialises an <em>instance</em> of the<em> class. </em> That is to say, whenever the<em> class</em> is <em>instantiated,</em> the <em>__init__</em> <em>method</em> runs (once).  Because it is a <em>method</em> (<em>function</em>), <em>arguments</em> can be passed to it, so that the <em>instance</em> of the <em>class</em> can be customised.</p>
<p>However, in order for the <em>class</em> to customise itself at the time it is being <em>instantiated,</em> it needs some way of referring to the particular instance, rather than to the attributes of the class.  So, in the <a href="http://python4kids.wordpress.com/2011/09/26/classy-attributes/">previous tutorial</a>, after we had created an <em>instance,</em> we could assign different values to the <em>attributes</em> <em>inherited</em> from the <em>class</em> by that <em>instance. </em> However, if <em>__init__</em> is part of the <em>class</em> definition, it is written before any <em>instances</em> are made, so it doesn&#8217;t know about any <em>instances. </em> How does it refer to an <em>instance</em> it doesn&#8217;t know about &#8211; especially when there may be multiple <em>instances</em> of a <em>class?</em></p>
<p>The answer is the &#8220;self&#8221; variable.  Self refers to&#8230; itself.  That is, when an <em>instance</em> <em>inherits</em> from a <em>class,</em> and the <em>class</em> refers to <em>self,</em> the <em>instance</em> reads that reference as a reference to &#8220;myself the instance&#8221; not &#8220;the class&#8217;s self&#8221;.  Using<em> &#8220;self&#8221;</em> is actually &#8220;only&#8221; a convention and it could be called something else (other languages use &#8220;my&#8221;).  You should always use &#8220;self&#8221; and not some other name.</p>
<p>Let&#8217;s have an example:</p>
<pre>&gt;&gt;&gt; class allDads(object):                                                                                                                                           
...    def __init__(self,age=28):                                                                                                                             
...       self.age = age                                                                                                                                                 
...                                                                                                                                                                                                                                                                                                                             
&gt;&gt;&gt; dad1 = allDads()
&gt;&gt;&gt; dad1.age
28                                                                                                                                                                       
&gt;&gt;&gt; dad2 = allDads(35)                                                                                                                                                   
&gt;&gt;&gt; dad2.age
35                        
&gt;&gt;&gt; dad1.age
28</pre>
<p>I printed <em>dad1.age</em> again to demonstrate  that, when we initiatlised <em>dad2</em>, <em>self</em> referred to <em>dad2</em>, and had no impact on the instance <em>dad1</em>.</p>
<p>You need to get comfortable using <em>self</em> and <em>__init__</em> because you will be using them <strong>a lot</strong>.</p>
<p><strong>Exercise:</strong></p>
<p>Rewrite the <em>allDads class</em> to add an <em>attribute</em> <em>self.appearance,</em> which is initialised by <em>__init__()</em>.  Make appearance default to &#8220;Hairy&#8221;.  Test it by making two <em>instances</em> <em>dad1</em> and <em>dad2,</em> passing an <em>argument</em> to appearance for <em>dad1,</em> but not for <em>dad2. </em> Print out <em>dad1.appearance</em> and <em>dad2.appearance</em> to confirm it worked properly.</p>
<p><strong>Notes:</strong></p>
<p>[1] Pronounced (among other ways) &#8220;dunder init&#8221; &#8211; see the <a href="http://python4kids.wordpress.com/2011/03/07/time-for-some-introspection/">Introspection post</a> for some comments on pronunciation.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/362/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/362/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/362/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=362&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/10/17/classy-methods-a-sense-of-self-classes-part-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Classy Attributes (Classes Part 1)</title>
		<link>http://python4kids.wordpress.com/2011/09/26/classy-attributes/</link>
		<comments>http://python4kids.wordpress.com/2011/09/26/classy-attributes/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 09:02:18 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=356</guid>
		<description><![CDATA[Suitably classy music starts. Mix through to Wilde&#8217;s drawing room. A crowd of suitably dressed folk are engaged in typically brilliant conversation, laughing affectedly and drinking champagne. Prince     My congratulations, Wilde. Your latest play is a great success. The whole of London&#8217;s talking about you. Oscar     There is only one thing in the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=356&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.ibras.dk/montypython/episode39.htm#4">Suitably classy music starts. Mix through to Wilde&#8217;s drawing room. A crowd of suitably dressed folk are engaged in typically brilliant conversation, laughing affectedly and drinking champagne.<br />
Prince     My congratulations, Wilde. Your latest play is a great success. The whole of London&#8217;s talking about you.<br />
Oscar     There is only one thing in the world worse than being talked about, and that is not being talked about.<br />
There follows fifteen seconds of restrained and sycophantic laughter&#8230;</a></em></p>
<p>Ok, now it&#8217;s time to draw breath a little and talk about something I mentioned a couple of tutorials ago &#8211; <em>classes.  </em> We&#8217;ve used heaps of classes so far without noticing them.  Classes are all round useful things,  and there&#8217;s absolutely no avoiding classes if you do any but the most trivial of programs in Python.  But that&#8217;s no problem because classes are really really neat and using them (generally) will improve your programming and your programs.  Once you start using them you&#8217;ll wonder how you ever did anything without them.</p>
<p>Let&#8217;s start by making a class:</p>
<pre>&gt;&gt;&gt; class allDads(object):                                                                                                                                                               
...   pass                                                                                                                                                                               
...                                                                                                                                                                                      
&gt;&gt;&gt; allDads
&lt;class '__main__.allDads'&gt;</pre>
<p>This defines a <em>class</em> called <em>allDads</em> (the <em>pass</em> statement is necessary, because Python expects a <em>class</em> to have <em>statements</em> setting out the innards of the <em>class. </em> We have used <em>pass</em> as a sort of do nothing innard.  We will do a more interesting example in a later tute).  The<em> class allDads</em> is said to &#8220;inherit from&#8221; <em>object</em> (ie the thing named in the brackets)<em>.</em>  Which is to say, all the functions and data that <em>object</em> has, <em>allDads</em> has as well. As everything in Python is an <em>object,</em> so too <em>allDads</em> is also an <em>object.</em> However, <em>allDads</em> is just a definition, it is not an <em>instance. </em> We can make an &#8220;instance&#8221; of <em>allDads</em> as follows:</p>
<pre>&gt;&gt;&gt; myDad = allDads()                                                                                                                                                                    
&gt;&gt;&gt; myDad                                                                                                                                                                                
&lt;__main__.allDads object at 0x7fa2c150f610&gt;</pre>
<p><a href="http://en.wikipedia.org/wiki/Nota_bene">Nota bene</a>: until you&#8217;re more familiar with classes, you should always define your <em>class</em> as <em>inheriting</em> from <em>object. </em> That is always put &#8220;(object)&#8221; after the name of the <em>class.</em></p>
<p>At the moment we&#8217;ve made a pretty boring class and a pretty boring instance.   The difference between <em>classes</em> and <em>instances</em> is that a class is a general description, while an instance is a particular.  Thus &#8220;all dads&#8221; is a class (that is, the class of men who are parents), but &#8220;my dad&#8221; is a particular instance of that class.</p>
<p>When classes store data it is called an<em> attribute</em>.  <em>Attributes</em> are referenced by joining the <em>class</em> name with the <em>attribute</em> name by a dot.  Here&#8217;s an example:</p>
<pre>&gt;&gt;&gt; allDads.appearance = "Hairy"</pre>
<p>Here &#8220;appearance&#8221; is the name of the attribute, right before we first try to assign a value to it Python creates it.  It has been assigned the <em>value</em> &#8220;Hairy&#8221;.  Let&#8217;s retrieve the <em>value</em> we&#8217;ve stored there:</p>
<pre>&gt;&gt;&gt; allDads.appearance
'Hairy'</pre>
<p>What&#8217;s more, since <em>myDad</em> is an <em>instance</em> of <em>allDads</em>, it has inherited the <em>attribute</em> from the assignment to the <em>class:</em></p>
<pre>&gt;&gt;&gt; myDad.appearance
'Hairy'</pre>
<p>However, the <em>class</em> doesn&#8217;t <em>inherit</em> from the instances (which makes sense &#8211; just because my dad has certain attributes doesn&#8217;t mean all dads do):</p>
<pre>&gt;&gt;&gt; myDad.description = "My dad is, like, so the best dad in the world.  What's more, he's particularly self effacing."
&gt;&gt;&gt; myDad.description
"My dad is, like, so the best dad in the world.  What's more, he's particularly self effacing."
&gt;&gt;&gt; allDads.description
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: type object 'allDads' has no attribute 'description'</pre>
<p>As far as Python is concerned the class <em>allDads</em> has no <em>attribute</em> called &#8220;<em>description</em>&#8220;, even though an <em>instance</em> of it (<em>myDad</em>) does.  Let&#8217;s make another instance:</p>
<pre>&gt;&gt;&gt; thatSmellyKidsDad = allDads()
&gt;&gt;&gt; thatSmellyKidsDad.appearance
'Hairy'
&gt;&gt;&gt; thatSmellyKidsDad.description
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: 'allDads' object has no attribute 'description'</pre>
<p>Here we&#8217;ve made a second <em>instance</em> of <em>allDads</em> called <em>thatSmellyKidsDad. </em> <em>thatSmellyKidsDad</em> <em>inherits</em> the <em>attribute</em> <em>appearance</em> that the <em>class</em> has, but it doesn&#8217;t have the <em>attribute</em> we gave to the specific <em>instance</em> <em>myDad. </em> The <em>inheritance</em> occurs at the time the <em>instance</em> is created.  If you change the value of an <em>instance</em> later it doesn&#8217;t affect the <em>attribute</em> stored in any other instance, even if the <em>attribute</em> is <em>inherited</em> from the same <em>class</em> <em>attribute.</em></p>
<p><strong>Exercise 1:</strong> assign a different value to <em>myDad.appearance</em> and see if it changes <em>thatSmellyKidsDad.appearance</em></p>
<p><strong>Exercise 2</strong>: assign a different value to <em>allDads.appearance</em> and see if it changes <em>myDad.appearance</em> and <em>thatSmellyKidsDad.appearance</em></p>
<p><strong>Exercise 3:</strong> make some other attributes for <em>myDad</em> or <em>thatSmellyKidsDad</em> and assign values to them.</p>
<p><strong>Hint:</strong></p>
<p>Use this function to show all the attributes you&#8217;ve been adding:</p>
<pre>def showAttributesOfInstance(c):
  for i in dir(c):
    if i[:2] != "__":  # not a reserved attribute or function
      if not callable(i): # not actually necessary as you can't define methods yet
         print "%s:\t%s"%(i,c.__getattribute__(i))

&gt;&gt;&gt; myDad.age = "28 and some months"
&gt;&gt;&gt; showAttributesOfInstance(myDad)
age:    28 and some months
appearance:     Hairy
description:    My dad is, like, so the best dad in the world.  What's more, he's particularly self effacing.</pre>
<p><strong>Extra Extra Bonus Points</strong>: understand how <em>showAttributesOfInstance()</em> uses introspection to do what it does.</p>
<p><strong>Looking Forward</strong></p>
<p>Just as you can store data in a class you can also store <em>functions</em> in a <em>class. </em> When data is stored in a <em>class</em> it&#8217;s called an <em>attribute. </em> When a <em>function</em> is stored in a <em>class,</em> it&#8217;s called a <em>method.</em> &#8211; But more on that later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/356/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=356&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/09/26/classy-attributes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Side Track &#8211; Global and Local Variables</title>
		<link>http://python4kids.wordpress.com/2011/08/29/side-track-global-and-local-variables/</link>
		<comments>http://python4kids.wordpress.com/2011/08/29/side-track-global-and-local-variables/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 13:07:41 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=335</guid>
		<description><![CDATA[&#8230; once a week there&#8217;s an excursion to the local Roman ruins where you can buy cherryade and melted ice cream and bleedin&#8217; Watney&#8217;s Red Barrel, and one night they take you to a local restaurant with local colour and colouring &#8230; In the previous tutorial, I used a strange and cumbersome approach to storing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=335&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span id="Eric"> <a href="http://www.ibras.dk/montypython/episode31.htm#7">&#8230; once a week there&#8217;s an excursion to the local Roman ruins where you can buy cherryade and melted ice cream and bleedin&#8217; Watney&#8217;s Red Barrel, and one night they take you to a local restaurant with local colour and colouring </a>&#8230;</span></p>
<p>In the previous tutorial, I used a strange and cumbersome approach to storing the data that I needed to keep track of the image files in the directory, the total number of images and what image we were up to.  Instead of just saving the current image number in a variable called currentImage I instead created a dictionary called indexes and a key called currentImage, then assigned the value to that key.  I did the same thing for totalImages as well.  You might, justifiably, be thinking &#8211; why didn&#8217;t we just use two variables called currentImage and totalImages?  This tutorial is going to try to explain that.</p>
<pre>Let's set up the dictionary using code from the previous tutorial:
&gt;&gt;&gt; indexes = {}  # create a dictionary
&gt;&gt;&gt; indexes['totalImages'] = 17 # 'totalImages is a key in the dictionary
&gt;&gt;&gt; # 17 is the perfectly random number (honest, no number is more random!)
... indexes['currentImage'] = 1</pre>
<p>Now let&#8217;s assign this value to a variable called currentImage:</p>
<pre>&gt;&gt;&gt; currentImage = 1</pre>
<p>Confirm what we&#8217;ve typed:</p>
<pre>&gt;&gt;&gt; indexes
{'currentImage': 1, 'totalImages': 17}
 &gt;&gt;&gt; currentImage
 1</pre>
<p>So far, so good.  The problem comes when we try to refer to these in a function.  Let&#8217;s define a function which tries to print them:</p>
<pre>&gt;&gt;&gt; def printIndexes():
 ...   print indexes
 ...
 &gt;&gt;&gt; printIndexes()
 {'currentImage': 1, 'totalImages': 17}</pre>
<p>Now, let&#8217;s do function which tries to print the value of currentImage:</p>
<pre>&gt;&gt;&gt; def printCurrentImage():
 ...     print currentImage
 ...
 &gt;&gt;&gt; printCurrentImage()
 1</pre>
<p>So far we haven&#8217;t had a problem.  However, in our slideshow application we needed to increment the value of currentImage, so let&#8217;s change our functions to do that:</p>
<pre>&gt;&gt;&gt; def incrementIndexes():
 ...   indexes['currentImage']+=1
 ...</pre>
<p>Confirm the starting values, run the function, then see what the ending values are after calling the function:</p>
<pre> &gt;&gt;&gt; indexes
 {'currentImage': 1, 'totalImages': 17}
 &gt;&gt;&gt; incrementIndexes()
 &gt;&gt;&gt; indexes
 {'currentImage': 2, 'totalImages': 17}</pre>
<p>Now, do the same for the variable currentImage:</p>
<pre>&gt;&gt;&gt; def incrementCurrentImage():
 ...    currentImage += 1
 ...
 &gt;&gt;&gt; currentImage
 1
 &gt;&gt;&gt; incrementCurrentImage()
 Traceback (most recent call last):
 File "&lt;stdin&gt;", line 1, in &lt;module&gt;
 File "&lt;stdin&gt;", line 2, in incrementCurrentImage
 UnboundLocalError: local variable 'currentImage' referenced before assignment</pre>
<p>This worked for the dictionary, but it all blew up when we tried to do the same thing with the variable.  Of note is the error message: local variable &#8216;currentImage&#8217; referenced before assignment.  This error can be avoided by use of the <em>global</em> keyword &#8211; but don&#8217;t avoid it this way:</p>
<pre>&gt;&gt;&gt; def incrementCurrentImage():
 ...    global currentImage
 ...    currentImage +=1
 ...
 &gt;&gt;&gt; currentImage
 1
 &gt;&gt;&gt; incrementCurrentImage()
 &gt;&gt;&gt; currentImage
 2</pre>
<p>The reason that the function failed originally is that Python was looking for a &#8216;local&#8217; variable.  That is, a variable whose name only makes sense while the program is within the function. Local variables serve an important function in allowing you to modularise your code and re-use the same variable names but with different meanings in different contexts.  Thus, in a function which is processing strings the variable currentValue can be doing something different to a variable with the same name called currentValue but in a different function processing (eg) dictionaries.   This is especially true with <a href="http://en.wikipedia.org/wiki/Recursion_%28computer_science%29">recursive functions</a> -but don&#8217;t expect to see any recursive functions here!</p>
<p>Unless you expressly tell Python otherwise, if a variable is <em>changed</em> inside a function, it is a local variable (if a variable is only read, then Python is happy to assume it&#8217;s a global variable &#8211; in a sense, it has to be because if it&#8217;s only read, it must have got its value somewhere outside the function).  This means it must be initialised within the function (since its name has no meaning outside the function).  If it hasn&#8217;t been initialised Python gets confused.  Hence the UnboundLocalError: it gave us.</p>
<p>How about this:</p>
<pre>&gt;&gt;&gt; aVariable = 1
 &gt;&gt;&gt; def incrementLocally():
 ...   aVariable = 1
 ...   aVariable += 1
 ...   print aVariable
 ...
 &gt;&gt;&gt; print aVariable
 1
 &gt;&gt;&gt; incrementLocally()
 2
 &gt;&gt;&gt; print aVariable
 1</pre>
<p>In this example, despite doing stuff to aVariable inside the function, the variable called aVariable that we started with has been unchanged.  Now try this:</p>
<pre>&gt;&gt;&gt; def incrementLocallyAgain(aVariable):
 ...    aVariable += 1
 ...    print aVariable
 ...
 &gt;&gt;&gt; print aVariable
 1
 &gt;&gt;&gt; incrementLocallyAgain(aVariable)
 2
 &gt;&gt;&gt; print aVariable
 1</pre>
<p>The same thing happened, even though we passed in aVariable as an argument to the function.   Within the function aVariable was a local variable.  It got a value when the function was started and that value was assigned locally.  Because local variables must be assigned a value before they are referenced it also follows that each time a function is called, its local variables are reset or reinitialised.  Indeed, each time the function is called, a whole new piece of memory is allocated to the function to run in.  This also means that local variables are not remembered from one invocation of the function to another (and even if they were, the need to initialise the variable would end up forgetting the old value anyway).</p>
<p>So, why did it work for a dictionary?  This is because dictionaries provide a level of indirection to the values stored in them.  The local functions never tried to assign a value to the name used by the dictionary, they only ever tried to assign a value to a key within the dictionary.  That is, they never said</p>
<p>indexes = 5</p>
<p>Rather, they said</p>
<p>indexes['someKey']=5.</p>
<p>So Python only looks up the dictionary.  When it doesn&#8217;t find it locally, it assumes it (the dictionary) is global.  From there it can access and change the values of keys in the dictionary.</p>
<p>You can see what values are local and global using two specific functions called <em>locals()</em> and<em> globals()</em> respectively.  These functions return a dictionary with the names and values of local and global variables respectively.  They are also additional examples of Python&#8217;s introspection as we discussed in our earlier tute.</p>
<pre>&gt;&gt;&gt; def incrementLocally():
...    aVariable = 1
...    aVariable += 1
...    print aVariable
...    print 'locals = ',locals()
...
&gt;&gt;&gt; aVariable = 6
&gt;&gt;&gt; incrementLocally()
2
locals =  {'aVariable': 2}
&gt;&gt;&gt; aVariable
6</pre>
<p>Usually you won&#8217;t need to worry about whether something is local or global because it will naturally be determined by the way you do your code.  As a rule of thumb you should avoid using &#8216;global&#8217; variables.  Unless you are very careful about their use, they can make your code very hard to understand and maintain.  If you need to make reference to a variable from within a function, then pass the variable in as a parameter to the function.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/335/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/335/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/335/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/335/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/335/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/335/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/335/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=335&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/08/29/side-track-global-and-local-variables/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Really GUI (more on Buttons, images and handlers)</title>
		<link>http://python4kids.wordpress.com/2011/08/22/really-gui-more-on-buttons-images-and-handlers/</link>
		<comments>http://python4kids.wordpress.com/2011/08/22/really-gui-more-on-buttons-images-and-handlers/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 01:34:31 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=333</guid>
		<description><![CDATA[In the last few tutorials we have been looking at various parts of what make up a graphical user interface.   We've created labels and buttons and have attached images to a label (and a button if you did the homework).  We have also associated an action with pressing a button.   In this tutorial we're going to put these together to make a simple image viewer application.  As with the previous tutorials, this will only work with images which are saved as a "gif" format.  Also, a word of warning - you need to do pretty much all of the code before any of it will work.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=333&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode38.htm#9"><em>Back to the photo sequence and music. Each photo is on the screen for only two seconds, and in between each there is a click as of a slide projector changing or even the sound of the shutter of a camera. The photos show in sequence: Anthony Barber, Katy Boyle, Edgar Allan Poe, a loony head and shoulders. He has ping-pong ball eyes, several teeth blocked out, a fright wig and his chest is bare but across it is written &#8216;A Loony&#8217;, Reginald Maudling, Tony Jacklin. A buzzer sounds.</em></a></p>
<p>In the last few tutorials we have been looking at various parts of what make up a graphical user interface.   We&#8217;ve created labels and buttons and have attached images to a label (and a button if you did the homework).  We have also associated an action with pressing a button.   In this tutorial we&#8217;re going to put these together to make a simple image viewer application.  As with the previous tutorials, this will only work with images which are saved as a &#8220;gif&#8221; format.  Also, a word of warning &#8211; you need to do pretty much all of the code before any of it will work.</p>
<p>Here are some images for you to use.  As with the earlier tutorial, you can either use &#8216;save as&#8217; to download a copy, or you can use the Python code in the note below to download them (if you use Python you should be in your python4kids directory when you do the download otherwise the files will get saved somewhere else).  A gold star if you use Python for the download.</p>
<p><a href="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage1.gif"><img class="alignnone size-full wp-image-337" title="p4kbuttonImage1" src="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage1.gif?w=630" alt=""   /></a><a href="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage2.gif"><img class="alignnone size-full wp-image-338" title="p4kbuttonImage2" src="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage2.gif?w=630" alt=""   /></a></p>
<p><a href="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage3.gif"><img class="alignnone size-full wp-image-339" title="p4kbuttonImage3" src="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage3.gif?w=630" alt=""   /></a><a href="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage4.gif"><img class="alignnone size-full wp-image-340" title="p4kbuttonImage4" src="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage4.gif?w=630" alt=""   /></a></p>
<p><strong>Planning</strong></p>
<p>When writing a program it is a good idea to plan out what tasks the program is intended to do first.  Then, when you write the program the plan can guide you from one component to another.  Also, you can write a plan as a comment at the start of your program and it can serve as a docstring &#8211; at least until you&#8217;ve gone back and written a proper docstring for your code.</p>
<p><strong>Exercise</strong>: Use your text editor to make a list of the things that would need to happen in order for a slide show program to run.   Save the list to a file called &#8216;p4kSlideshow.py&#8217; in your python4kids directory.   Make your edits to this file.  Enclose the list in triple quotes -&gt;</p>
<pre>'''
item 1  (and explanation)

item 2 etc

...

'''</pre>
<p><strong>Solution:</strong></p>
<p>The things that I think a slideshow should do are:</p>
<ul>
<li>make a list of all the images in the directory</li>
<li>get the first image and display it</li>
<li>on user input, display the next image (in this case, user input will be a button click)</li>
<li>when all images have been displayed exit.</li>
</ul>
<p>My list of things will likely be different from your list of things.  For example, you might want the images to be displayed in a random order, or when you get to the end of the images you might want to start again from the beginning, or you might want the user to choose the image to show from a list.  There are many ways of approaching it.  I&#8217;m showing you something simple, but if you&#8217;ve got other things on your list, extend the work we do here and implement them in your own program.</p>
<p>Here&#8217;s my note:</p>
<pre>'''
 p4kSlideshow
 When run in a directory this program:
 * searches the directory for files with a '.gif' extension
 * displays the first image it finds
 * when a user clicks, it displays the next image
 * if user clicks last image, the program exits.
'''</pre>
<p>The benefit of doing this is it tells us what to do (and, hopefully, also in what order &#8211; in our case we are dealing with a handler so it&#8217;s a little mixed up). It&#8217;s our map to completing the program.  Let&#8217;s do the first one.</p>
<p><strong>Coding</strong></p>
<p>We are going to use a function from the <em>os</em> module called <em>os.listdir</em> (we have used this <a href="http://python4kids.wordpress.com/2010/09/29/filing/">before</a>) and another called <em>os.path.splitext</em>.  Splitext splits a file into its base file name and its extension so <em>thisfile.txt</em> would become<em> ['thisfile','.txt']</em>.  We do this to identify which files are gif files.  We could have also used the slicing operator [-3:] (reminder &#8211; <a href="http://python4kids.wordpress.com/2010/08/04/string/">see here</a>):</p>
<pre>import os

IMAGE_EXTENSIONS=['.gif']
listOfFiles = os.listdir('.')
# list dir doesn't necessarily give alphabetical order so we sort
listOfFiles.sort()
listOfImages = []
for f in listOfFiles:
  if os.path.splitext(f)[-1] in IMAGE_EXTENSIONS:
    listOfImages.append(f)</pre>
<p>Note that there&#8217;s a &#8216;[-1]&#8216; after <em>splitext(). </em> This is because <em>splitext</em> returns  a list, with the last entry in the list ([-1] means last in the list) being the extension.  This code stores a list of images in the list named <em>listOfImages.</em></p>
<p>Now we do the GUI bit.  We need to add the Tkinter import at the start of the file:</p>
<pre>import os
from Tkinter import *</pre>
<p>We also need to keep track of how many images there are, and which image it is that we are currently up to:</p>
<pre>indexes = {}
'''
indexes is a dictionary containing some values
that we need to keep track of.
I am using a dictionary rather than two variables (say totalImages and currentImage)
so that I don't have to explain global and local variables to you yet (maybe next tute?)
'''
indexes['totalImages'] = len(listOfImages)
if indexes['totalImages'] &lt;1:
 sys.exit()</pre>
<p>After that we set up a button:</p>
<pre># set up the GUI

displayButton = Button(None,text= "If you can see this text, there's something wrong")
# we shouldn't ever see the text
# we could leave the text= parameter out

displayButton.pack()</pre>
<p>Now we create a function to handle clicks.  Later we will need to point the button&#8217;s &#8216;command&#8217; key at this function.</p>
<pre>def nextImage():
  indexes['currentImage'] += 1 
  # += 1 says "add one to the current value of this variable"
  if indexes['currentImage'] == indexes['totalImages']:
    # if past last image, then exit
    # as the list starts at index 0 and runs to the number of entries -1
    # it will reach the last one on total entries -1, if it's equal to totalImages
    # then when we added one, we went past the last one, so exit instead of displaying.
    sys.exit()
  else:
    imageIndex = indexes['currentImage']

  imageFile = listOfImages[imageIndex]
  print "imageFile = %s"%imageFile
  # this is just for debugging, you can remove the print statement if you want
  imageObject = PhotoImage(file=imageFile)
  displayButton['image']=imageObject
  displayButton.image=imageObject # NOTE: WON'T WORK WITHOUT THIS BIT OF SORCERY!
  displayButton.pack()</pre>
<p>Note the note!  This assignment really is sorcery.  If you remove it your program (probably) won&#8217;t work!  Moreover, if I didn&#8217;t tell you there&#8217;s no way you&#8217;d work it out for yourself.  What this line does is it forces Python to keep a reference to the <em>imageObject. </em> Because of the way Tkinter does the assignment <em>displayButton['image'],</em> Python does not keep a reference to the object <em>imageObject. </em> Because it has not kept a reference, Python thinks the object is not being used (even though it is). Python therefore throws the <em>imageObject</em> out in order to save memory.  This process is called &#8220;garbage collection&#8221; and is happening all the time in Python.  When we do the assignment <em>displayButton.image=imageObject</em> we force Python to remember the object and therefore not to throw it out with the rest of the garbage.</p>
<p><strong>Exercise:</strong> once you&#8217;ve finished the tute comment out the line<em> displayButton.image=imageObject</em> run it again and see what happens.</p>
<p>We are just about ready now.   For the function <em>nextImage()</em> to work the entry <em>indexes['currentImage']</em> needs to be initialised. We also need to display the first image and hook up the function to the button click.  These are all pretty easy:</p>
<pre># initialise the index we will use to display the images.
indexes['currentImage'] = -1</pre>
<p>We use -1 here so that on the first call to nextImage 1 will be added to it, giving 0 (-1+1=0) and 0 is the first entry of the list of file names we just created.</p>
<p>Display the first image:</p>
<pre>nextImage()</pre>
<p>Hook up the <em>nextImage</em> function to be run when the button is clicked:</p>
<pre>displayButton['command']=nextImage</pre>
<p>Now, we need to start the program waiting for mouse clicks.  This has not been something we&#8217;ve done in the past few tutes because we were using an interactive Python session.  However, now we&#8217;re going to need it.  We do this by calling the &#8216;mainloop()&#8217; method:</p>
<pre>displayButton.mainloop()</pre>
<p>Ta da! We&#8217;re done (<strong>exercise:</strong> check that we&#8217;ve implemented everything in our original list).  Run this program from your command line like this:</p>
<pre>&gt; python p4kSlideshow.py</pre>
<p>and you should have a simple slideshow.  You must make sure you&#8217;ve got the gif files saved in the same directory though!</p>
<p>When the program hits the <em>mainloop()</em> function it sort of slips into a Tkinter Netherworld, in which you don&#8217;t really see what it&#8217;s doing.  It is only when Tkinter notices a mouse click on the button that control comes back to your program (executing the handler function <em>nextImage()). </em> Even then, when <em>nextImage()</em> finishes running, program execution passes back into Tkinter and you can&#8217;t see what&#8217;s happening there.</p>
<p>There are a lot of limitations with this program.  Most obviously it only works with <em>.gif</em> files! Argh!  However, it has other problems.  First, you can&#8217;t go backwards &#8211; it&#8217;s one way from start to finish, and then the program ends.  You might want to start the slideshow from the start again.  Second,  it is quite fragile.  If one of the files is deleted, renamed or moved half way through your slide show (ie after running os.listdir() but before displaying the file) then you&#8217;re going to have a problem.  The program doesn&#8217;t check that the filename remains valid.  The program is unhelpful if there are no gif files in the directory (simply exiting).  There are many ways the program could be improved.  If you are game, have a go!</p>
<p><strong>Exercise:</strong> change the program so that, once it displays all of the images it begins again with the first one.</p>
<p><strong>Hint:</strong> at the end of the function <em>nextImage()</em> test to see if you&#8217;re at the end of the images and, if so, assign a certain value to<em> indexes['currentImage']</em>. <em></em></p>
<p>This was quite a complex program because we had to knit three components together.  Moreover, handlers are pretty difficult conceptually.  If you can follow what&#8217;s happening and get it running, give yourself a gold star.</p>
<p><strong>Notes:</strong></p>
<p><strong>Downloading the images:</strong></p>
<pre>&gt;&gt;&gt; imageLinks = ["http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage1.gif", "http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage2.gif", "http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage3.gif", "http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage4.gif"]
&gt;&gt;&gt; import urllib
&gt;&gt;&gt; for i in imageLinks:
...     filename =  i[-19:]   # [-19:] was trial and error and based on a set length of the filename
...     urllib.urlretrieve(i,filename)</pre>
<p><strong>The complete code:</strong></p>
<pre># -*- coding: utf-8 -*-
'''
p4kSlideshow
When run in a directory this program:
* searches the directory for files with a '.gif' extension
* displays the first image it finds
* when a user clicks, it displays the next image
* if user clicks last image, the program exits.
'''

import os
from Tkinter import *

IMAGE_EXTENSIONS=['.gif']

listOfFiles = os.listdir('.')
# list dir doesn't necessarily give alphabetical order so we sort
listOfFiles.sort()
listOfImages = []
for f in listOfFiles:
  if os.path.splitext(f)[-1] in IMAGE_EXTENSIONS:
    listOfImages.append(f)

# some print statements I used for debugging the code:
#print listOfFiles
#print listOfImages

# if there are no image files, then stop!

indexes = {}
'''
indexes is a dictionary containing some values
that we need to keep track of.
I am using a dictionary rather than two variables (say totalImages and currentImage)
so that I don't have to explain global and local variables to you yet (maybe next tute?)
'''

indexes['totalImages'] = len(listOfImages)
if indexes['totalImages'] &lt;1:
  sys.exit()

# set up the GUI

displayButton = Button(None,text= "If you can see this text, there's something wrong")
# we shouldn't ever see the text
# we could leave the text= parameter out

displayButton.pack()

# create a function to handle clicks

def nextImage():
  indexes['currentImage'] += 1
  # += 1 says add one to this variable
  if indexes['currentImage'] == indexes['totalImages']:
    # if past last image, then exit
    # as the list starts at index 0 and runs to the number of entries -1
    # it will reach the last one on total entries -1, if it's equal to totalImages
    # then when we added one, we went past the last one, so exit instead of displaying.
    sys.exit()
  else:
    imageIndex = indexes['currentImage']

  imageFile = listOfImages[imageIndex]
  print "imageFile = %s"%imageFile
  # this is just for debugging, you can remove the print statement if you want
  imageObject = PhotoImage(file=imageFile)
  displayButton['image']=imageObject
  displayButton.image=imageObject # NOTE: WON'T WORK WITHOUT THIS BIT OF SORCERY!
  displayButton.pack()

# initialise the index we will use to display the images.
indexes['currentImage'] = -1
'''
-1 is a bit of a magic number
We use -1 because the nextImage function below adds one each time it is called
so the first time it is called it will display the image at location 0 (-1+1 =0)
the next time it is called it will display the image at location 1 and so on
'''

# display the first image
nextImage()

# set the button to run the nextImage function when clicked
displayButton['command']=nextImage

# Now start the program waiting for mouse clicks
# when you click the button it will run the nextImage function
displayButton.mainloop()</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/333/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/333/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/333/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=333&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/08/22/really-gui-more-on-buttons-images-and-handlers/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage1.gif" medium="image">
			<media:title type="html">p4kbuttonImage1</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage2.gif" medium="image">
			<media:title type="html">p4kbuttonImage2</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage3.gif" medium="image">
			<media:title type="html">p4kbuttonImage3</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4kbuttonimage4.gif" medium="image">
			<media:title type="html">p4kbuttonImage4</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Images in the GUI</title>
		<link>http://python4kids.wordpress.com/2011/08/08/using-images-in-the-gui/</link>
		<comments>http://python4kids.wordpress.com/2011/08/08/using-images-in-the-gui/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 04:49:14 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=317</guid>
		<description><![CDATA[Gladys leaps over to the tape deck, presses levers and switches. Sound of tape reversing. There is a hum and lights flash on and off. A blurred image of a lady in the street comes up on one of the monitors. In this tutorial we look at using images in a GUI environment.  One of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=317&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode33.htm#4"><em>Gladys leaps over to the tape deck, presses levers and switches. Sound of tape reversing. There is a hum and lights flash on and off. A blurred image of a lady in the street comes up on one of the monitors.</em></a></p>
<p>In this tutorial we look at using images in a GUI environment.  One of the possible attributes which can be assigned to a Label or Button widget is an image.   You will surely have seen many buttons with images on them.   Every time you see a toolbar in a program, each of the images on it is itself on a button widget.  In order to do this tutorial though there are a couple of issues:</p>
<ul>
<li>first, you need to have images in the Python4kids directory we set up several tutorials ago.  You also need to start Python from within that directory.</li>
<li>second, unless you install something called the Python Imaging Library (PIL), Python can only handle a few limited types of image file.  One of the file types which will work is .gif, which we will be using here. This tutorial <strong>will not work</strong> with jpeg files.</li>
<li>third, you need to have the gif files we&#8217;re going to use in your python for kids directory.</li>
</ul>
<p>If you have some gifs that you&#8217;d prefer to use, by all means copy them into your python for Kids directory.  However, if you can&#8217;t, here is an outrageously boring gif  (it is  just a screencapture from the previous tutorial) for you to download and save:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110726b.gif"><img class="alignnone size-full wp-image-322" title="p4kTkinter110726B" src="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110726b.gif?w=630" alt=""   /></a></p>
<p>Download and save this gif image by right-clicking the images in the previous tutorial and selecting &#8220;Save Link As&#8221; (you may also be able to drag and drop images from the web page into your folder) [* or do it in Python (below)].  Remember to save it to the Python for kids directory that you set up in <a href="http://python4kids.wordpress.com/2011/05/02/catching-our-breath/">this tutorial</a>.  You don&#8217;t need to change the file name.   If you have your own image file(s) you&#8217;d like to use, then, by all means put them in your Python4kids directory instead but make sure it is a &#8216;.gif&#8217; file.  You can convert images from .jpg to gif using third party programs such as <a href="http://www.gimp.org/">GIMP</a>.</p>
<p><a><img class="alignnone size-full wp-image-318" title="p4ktkinter110804" src="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110804.jpeg?w=630&#038;h=196" alt="" width="630" height="196" /></a></p>
<p>As before we import from Tkinter:</p>
<pre>&gt;&gt;&gt; from Tkinter import *
&gt;&gt;&gt; labelWidget = Label(None)
&gt;&gt;&gt; # Notice we haven't set the text?</pre>
<p>Next, we make a PhotoImage object from the file (taking note of the file&#8217;s name as we downloaded it)</p>
<pre>&gt;&gt;&gt; imgFile = 'p4ktkinter110726b.gif'
&gt;&gt;&gt; imageObject = PhotoImage(file = imgFile)</pre>
<p>Watch the &#8220;file = &#8221; syntax here.  We haven&#8217;t attached the file to the labelWidget yet.  We&#8217;ll do that very soon.  However, now if we:</p>
<pre>&gt;&gt;&gt; labelWidget.pack()</pre>
<p>You&#8217;ll see that we get a really small labelWidget with nothing in it. You might need to resize it to see much of it at all.</p>
<p>So let&#8217;s put the image we have into the labelWidget:</p>
<pre>&gt;&gt;&gt; labelWidget['image']=imageObject</pre>
<p>Note here that we are using the dictionary associated with labelWidget, you should be able to tell that because of the square brackets and the key which is inside single quotes.  At this point the object should automagically appear in the widget &#8211; if you haven&#8217;t resized the window yet you may need to in order to see the image:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110805.jpeg"><img class="alignnone size-full wp-image-324" title="p4kTkinter110805" src="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110805.jpeg?w=630" alt=""   /></a></p>
<p>It looks like there is a window inside the window, but there isn&#8217;t.  It&#8217;s just an image (try opening up the gif file and changing it with a paint package if you have one and then redoing the tutorial).  Clicking the buttons won&#8217;t have any effect.</p>
<p><strong>Homework:</strong></p>
<p>Display an image on a Button</p>
<p><strong>* Extension: Downloading the file using Python:</strong></p>
<pre>&gt;&gt;&gt; url = "http://python4kids.files.wordpress.com/2011/08/p4ktkinter110726b.gif"
&gt;&gt;&gt; fileName = url[-21:]
&gt;&gt;&gt; fileName
'p4ktkinter110726b.gif'
&gt;&gt;&gt; import urllib
&gt;&gt;&gt; urllib.urlretrieve(url,fileName)
('p4ktkinter110726b.gif', &lt;httplib.HTTPMessage instance at 0x82695ac&gt;)</pre>
<p>This relies only on knowing what the url of the image file is.  We&#8217;re using the urlretrieve function of the <a href="http://docs.python.org/library/urllib.html">urllib module</a>.  It will work for urls which are not images as well.  In order to download a file it needs to know the url of the file (ie what you would type into a web browser to surf to the file) and a file name to save the to on your computer.</p>
<p>A word of warning though &#8211; sometimes a network is set up so you that this will not work.  If you have trouble, better to just save as with your browser.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/317/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=317&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/08/08/using-images-in-the-gui/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110726b.gif" medium="image">
			<media:title type="html">p4kTkinter110726B</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110804.jpeg" medium="image">
			<media:title type="html">p4ktkinter110804</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/08/p4ktkinter110805.jpeg" medium="image">
			<media:title type="html">p4kTkinter110805</media:title>
		</media:content>
	</item>
		<item>
		<title>Button it up (Buttons and event handlers)</title>
		<link>http://python4kids.wordpress.com/2011/07/27/button-it-up-buttons-and-event-handlers/</link>
		<comments>http://python4kids.wordpress.com/2011/07/27/button-it-up-buttons-and-event-handlers/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 06:22:08 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=297</guid>
		<description><![CDATA[Cut to the gift department. A large lady is standing by counter holding a large cylinder with a rose attachment. Lady     Yes this looks the sort of thing. May I just try it? Assistant     Certainly, madam. The lady presses button and a sheet of flame shoots out across the hall. Lady     Oh! [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=297&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.ibras.dk/montypython/episode41.htm">Cut to the gift department. A large lady is standing by counter holding a large cylinder with a rose attachment.<br />
Lady     Yes this looks the sort of thing. May I just try it?<br />
Assistant     Certainly, madam.<br />
The lady presses button and a sheet of flame shoots out across the hall.<br />
Lady     Oh! Sorry! So sorry! (she is happy though) Yes that&#8217;s fine. </a></em></p>
<p>We&#8217;re having a look at another kind of widget today, as well as seeing some stuff about &#8220;event handling&#8221;. The widget we&#8217;re looking at is the Button &#8211; it&#8217;s what has &#8220;Ok&#8221; on it when you get a pop up dialog.   The process is much the same as what we did last time for labels:</p>
<pre>&gt;&gt;&gt; from Tkinter import *
&gt;&gt;&gt; b1 = Button(None, text="This is a button.  Can you see it has some edges that the label didn't have?")
&gt;&gt;&gt; b1.pack()</pre>
<p>This should give you a button that looks like this:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726a.jpeg"><img class="alignnone size-full wp-image-302" title="p4kTkinter110726A" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726a.jpeg?w=630" alt=""   /></a></p>
<p>Now let&#8217;s do something zany  and add another one:</p>
<pre>&gt;&gt;&gt; b2 = Button(None, text="Click me!")
&gt;&gt;&gt; b2.pack()</pre>
<p>Here&#8217;s the pic:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726b.jpeg"><img class="alignnone size-full wp-image-303" title="p4kTkinter110726B" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726b.jpeg?w=630" alt=""   /></a></p>
<p>Can you see that the second button has appeared below the first button?  It is also in the middle, rather than on either of the sides.  Notice now that the <em>pack()</em> method has brackets (which indicates it&#8217;s a <em>function</em>?).   Have a look at the function&#8217;s help info to see more details about the parameters that the <em>pack()</em> method accepts:</p>
<pre>&gt;&gt;&gt; help(b2.pack)</pre>
<p>Let&#8217;s try one of them (make sure you can see the window with the buttons in it when you hit enter for this line):</p>
<pre>&gt;&gt;&gt; b2.pack(side=LEFT)</pre>
<p>Did you see the Button move?</p>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726c.jpeg"><img class="alignnone size-full wp-image-304" title="p4kTkinter110726C" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726c.jpeg?w=630" alt=""   /></a></p>
<p>You can try <em>side=RIGHT</em> on your own.</p>
<p>You can change the text of these buttons if you want:</p>
<pre>&gt;&gt;&gt; b2['text']='hi'

<a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726d1.jpeg"><img class="alignnone size-full wp-image-306" title="p4kTkinter110726D" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726d1.jpeg?w=630" alt=""   /></a></pre>
<p>Each of these buttons has associated with it a dictionary &#8211; which you should have noticed because of the use of the square brackets [] with an index which is not a number.  What we did above was change the value of the key &#8216;text&#8217; in b2&#8242;s dictionary.  To see all of the <em>keys</em> we in the <em>dictionary</em> use the standard <em>.keys()</em> <em>method</em> of <em>dictionaries:</em></p>
<pre>&gt;&gt;&gt; b2.keys()
['activebackground', 'activeforeground', 'anchor', 'background', 'bd', 'bg', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'default', 'disabledforeground', 'fg', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength']</pre>
<p>Changing the values of these keys will change various characteristics of the <em>Button. </em> Let&#8217;s put the text back the way it was:</p>
<pre>&gt;&gt;&gt; b2['text']="Click me!"</pre>
<p>Now, if you actually click one of these buttons you&#8217;ll see that it changes visually (more or less as you would expect a button to &#8211; it may look a little different from the buttons you&#8217;re used to because its styling comes from Tkinter not your operating system).  However, you&#8217;ll also notice that it doesn&#8217;t actually do anything.  This should not come as a surprise, given that we have just created a button but haven&#8217;t told Python what to do when the button is pressed.</p>
<p>So, let&#8217;s do that.  In the list of keys above, there is a key called &#8216;command&#8217;.  It&#8217;s currently empty:</p>
<pre>&gt;&gt;&gt; b2['command']
 ''</pre>
<p>This is where we tell Python what to do when the button is pressed.   The &#8216;command&#8217; key expects to receive the name of a function, so we need to create a function, then set the &#8216;command&#8217; key as the name of that function.  I start by setting up two constants in order to avoid spelling errors:</p>
<pre>&gt;&gt;&gt; B2BASETEXT="Click me!"
&gt;&gt;&gt; B2ALT_TEXT="Click me again!"
&gt;&gt;&gt; def b2Click():
 ...    if b2['text']== B2BASETEXT:
 ...       b2['text']=B2ALT_TEXT
 ...       b2.pack(side=RIGHT)
 ...    else:
 ...       b2['text']=B2BASETEXT
 ...       b2.pack(side=LEFT)</pre>
<p>Once that is done, we set the command:</p>
<pre>&gt;&gt;&gt; b2['command']=b2Click</pre>
<p>Now clicking the button should bounce it from one side of the window to the other, changing the text each time*[see note below]:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726e.jpeg"><img class="alignnone size-full wp-image-309" title="p4kTkinter110726E" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726e.jpeg?w=630" alt=""   /></a></p>
<p>However, we could have put anything at all in that function<em> b2Click()</em>, and that&#8217;s a really powerful idea.  The only problem is that Tkinter won&#8217;t let you pass arguments to the function.  However, not only is this not actually a problem for us at the moment (it&#8217;s not something we need to do), there&#8217;s also a way around it so it&#8217;s not really a problem at all.</p>
<p>So, let&#8217;s add quit button:</p>
<pre>&gt;&gt;&gt; b3 = Button(None,text="Click here to quit (without further warning)", command=quit)
&gt;&gt;&gt; b3.pack()</pre>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726f.jpeg"><img class="alignnone size-full wp-image-310" title="p4kTkinter110726F" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726f.jpeg?w=630" alt=""   /></a></p>
<p>If you click this new button, Python&#8217;s quit() function is run.  That will close the windows &#8211; and, indeed, exit Python as well.  This buggers up my console (new lines don&#8217;t work properly).  If you have this problem the <em>reset</em> command from the console should work (:&gt; reset).  Normally if you have a &#8220;quit&#8221; command it may result in users losing data they haven&#8217;t saved, so you will usually give users a warning to confirm they really want to quit.  You would probably &#8220;wrap&#8221; this call to <em>quit()</em> inside a separate function which asks the user to confirm that they want to quit.</p>
<p>Clicking a Button (or, indeed any other part of the window) is called an &#8220;event&#8221;.  The function which does something when you click the button is called a &#8220;handler&#8221; (also &#8220;event handler&#8221; or &#8220;callback handler&#8221;).</p>
<p>Another thing to notice here is where the third button ended up (since we didn&#8217;t specify a side to pack it on).  All I&#8217;m going to say about this is that laying out a user interface with Tkinter can be a little difficult to understand.  We&#8217;ll talk more about layout later.</p>
<p>Notes:</p>
<p>* the proper way to do this is to start up Tkinter&#8217;s<em> mainloop()</em> <em>method. </em> We will do this later (and if your clicks don&#8217;t seem to work let me know!) This <em>method</em> does the job of listening for <em>events</em> (clicking the mouse on a button is an &#8220;event&#8221;) generating messages and communicating them to <em>callback handlers</em> (in this case the <em>function</em> b2Click is a <em>callback handler</em>).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/297/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/297/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/297/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=297&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/07/27/button-it-up-buttons-and-event-handlers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726a.jpeg" medium="image">
			<media:title type="html">p4kTkinter110726A</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726b.jpeg" medium="image">
			<media:title type="html">p4kTkinter110726B</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726c.jpeg" medium="image">
			<media:title type="html">p4kTkinter110726C</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726d1.jpeg" medium="image">
			<media:title type="html">p4kTkinter110726D</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726e.jpeg" medium="image">
			<media:title type="html">p4kTkinter110726E</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110726f.jpeg" medium="image">
			<media:title type="html">p4kTkinter110726F</media:title>
		</media:content>
	</item>
		<item>
		<title>Tkinter tinkering (Graphical User Interfaces)</title>
		<link>http://python4kids.wordpress.com/2011/07/18/tkinter-tinkering-graphical-user-interfaces/</link>
		<comments>http://python4kids.wordpress.com/2011/07/18/tkinter-tinkering-graphical-user-interfaces/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 07:40:46 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=286</guid>
		<description><![CDATA[Man     Shut up! (It goes quiet next door) That&#8217;s better. He walks to a side wall and hangs his club on a hook beneath big old-fashioned art-nouveau sign clearly labelled `The Burlington Wall-banger&#8217;. He goes across to bed and gets in. In the bed are a party of four Japanese businessmen in suits with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=286&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode43.htm#5">Man     Shut up! (It goes quiet next door) That&#8217;s better.<br />
He walks to a side wall and hangs his club on a hook beneath big old-fashioned art-nouveau sign clearly labelled `The Burlington Wall-banger&#8217;. He goes across to bed and gets in. In the bed are a party of four Japanese businessmen in suits with lapel badges, two lady American tourists with rain hats and cameras, three other moustached English gentlemen in pyjamas, four Tour De France riders, three Swedish businessmen, and Winston Churchill. </a></p>
<p>So far we have been dealing with a command line interface for working with our Python programs.  While command lines are good for a lot of things, they&#8217;re usually pretty bad for interfacing with a general user of the program who doesn&#8217;t know how the various pieces work.  What we are going to look at now is a different way of presenting the program to a user (and probably a way that you are more familiar with) &#8211; GUIs.   GUI stands for &#8220;Graphical User Interface&#8221;.</p>
<p>In order to use a GUI, we need to use an external module to do all the grunt work behind making the interface components and presenting them to the end user.  There are a number of different modules which can be used.  We are going to use one called &#8220;<a href="http://docs.python.org/library/tkinter.html">Tkinter</a>&#8220;.  We are going to use Tkinter because it should come as part of every Python installation, so there&#8217;s no additional downloading to do, nor any need to get the Responsible Adult involved &#8211; but leave a comment if you have problem with Tkinter.</p>
<p>To start using Tkinter is pretty easy.  You do this:</p>
<pre>&gt;&gt;&gt; from Tkinter import *</pre>
<p>and&#8230; absolutely nothing should happen!</p>
<p><strong>DANGER WILL ROBINSON!</strong></p>
<p>A word of warning here: as a general rule using <em>&#8220;from X import *&#8221;</em>  is considered really bad form in Python because it means every object (* is a &#8220;wildcard&#8221; and means everything) is imported by its own name into your program, rather than part of the X <em>namespace.  </em> So, in our previous examples we&#8217;ve used <em>import random</em>, then accessed the <em>randint()</em> <em>function</em> via the random namespace: <em>random.randint()</em>. Had we used from random import *, then we could have said <em>randint()</em> and not <em>random.randint()</em>.  However, this would be a bad thing to do.  If you have two packages X and Y, each of which has its own object called x, then, if you use &#8220;import *&#8221; the two objects X.x and Y.x will both end up in your program called &#8216;x&#8217;.  As you don&#8217;t have the X and Y namespaces to distinguish them, they &#8216;collide&#8217;.</p>
<p>So, why am I using &#8220;import *&#8221; for you?  Because Tkinter is an exception.  The Tkinter package has been designed so that as few objects as possible are imported into your program, and because their names are specifically GUI related, so there is less risk of a naming collision.  If you are feeling uneasy about all this do multiple imports of the specific Tkinter components you need.</p>
<p><strong>Hello World in the GUI</strong></p>
<p>Graphical User Interfaces use a specific, common set of graphical components to display information to a user and to get feedback from them.  These components are called &#8220;widgets&#8221;.  As you are using a graphical interface all of the time, you are actually already aware of widgets, but you just don&#8217;t realise that they&#8217;re there.  So, for example, whenever you are presented with an &#8220;Ok/Cancel&#8221; dialog on the computer, the text of the dialog (&#8220;About to delete all your files&#8221;) is presented in a<em> &#8220;Label&#8221;</em> widget, while the &#8220;Ok&#8221; and &#8220;Cancel&#8221; are<em> &#8220;Button&#8221;</em> widgets.</p>
<p>So let&#8217;s do a label:</p>
<pre>&gt;&gt;&gt; labelWidget = Label(None,text="Hello Python4Kids!")  # note: None has a capital</pre>
<p>When you hit return you should see something like this (note: if you are running python-idle, this won&#8217;t work &#8211; at least not yet, run Python from a command line shell.  If you don&#8217;t know what python-idle is, you can ignore this note):</p>
<div id="attachment_287" class="wp-caption alignnone" style="width: 218px"><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110718.jpg"><img class="size-full wp-image-287 " title="A Tkinter window" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110718.jpg?w=630" alt=""   /></a><p class="wp-caption-text">A Tkinter window</p></div>
<p>Python has told <em>Tkinter</em> it&#8217;s going to need a window to put a <em>Label</em> <em>widget</em> in.  Tkinter has asked the operating system to give it a window and the operating system has given it a default window.  Along the top of the window are a number of <em>widgets</em> which have been provided by your operating system (not Python).  Your window may look a little different if you&#8217;re running an alternative operating system.   On my system above, there are 6 <em>widgets</em> &#8211; from left to right, a <em>menu</em> <em>widget</em> (X), a <em>button</em> (to pin this window across multiple desktops), a <em>label</em> &#8216;tk&#8217;, and three more <em>buttons</em> (minimise, maximise and close).  You might have a different set of operating system <em>widgets.</em></p>
<p>Where is the label we defined? Well, it exists:</p>
<pre>&gt;&gt;&gt; labelWidget
&lt;Tkinter.Label instance at 0x7fcf9966e368&gt;</pre>
<p>However, it&#8217;s not visible yet.  It&#8217;s not visible yet because we haven&#8217;t defined a &#8220;geometry&#8221; for it.   We do this through a <em>function</em> which is part of the widget called <em>.pack()</em> (<em>.pack()</em> is called a <em>&#8216;method&#8217;</em> of the <em>widget,</em> but we haven&#8217;t done that yet).</p>
<p>Debugging tip:  If you can&#8217;t see your widget, make sure you&#8217;ve .pack()ed it.</p>
<p>So let&#8217;s .pack() it:</p>
<pre>&gt;&gt;&gt; labelWidget.pack()</pre>
<p>The <em>.pack()</em> method can take a heap of arguments, which define how the widget is to be placed within the window.  As we only have a single widget, we just use the default packing, and therefore put no arguments in.   You should see the tk window above change to look something like this:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110719b.jpeg"><img class="alignnone size-full wp-image-288" title="p4kTkinter110719B" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110719b.jpeg?w=630" alt=""   /></a></p>
<p>One of the widgets in the title bar is obscured here (only four are visible), but grabbing the bottom right hand corner of the window will resize it allowing you to see the lost widgets:</p>
<p><a href="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110720c.jpeg"><img class="alignnone size-full wp-image-289" title="p4kTkinter110720C" src="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110720c.jpeg?w=630" alt=""   /></a></p>
<p>To close the window click the close button in the top right corner.</p>
<p>That&#8217;s it for now, more on GUIs in the coming tutes.</p>
<p>PS:</p>
<p>Did you notice that we did a basic GUI interface in only three lines of code (including the import statement)???  Is that amazing?</p>
<p>PPS:</p>
<p>Hello to visitors from the Podnutz webcast.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/286/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=286&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/07/18/tkinter-tinkering-graphical-user-interfaces/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110718.jpg" medium="image">
			<media:title type="html">A Tkinter window</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110719b.jpeg" medium="image">
			<media:title type="html">p4kTkinter110719B</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/07/p4ktkinter110720c.jpeg" medium="image">
			<media:title type="html">p4kTkinter110720C</media:title>
		</media:content>
	</item>
		<item>
		<title>Talk to your Teddy (Debugging)</title>
		<link>http://python4kids.wordpress.com/2011/06/25/talk-to-your-teddy-debugging/</link>
		<comments>http://python4kids.wordpress.com/2011/06/25/talk-to-your-teddy-debugging/#comments</comments>
		<pubDate>Sat, 25 Jun 2011 07:02:58 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=268</guid>
		<description><![CDATA[Presenter     Good evening. Tonight &#8216;Spectrum&#8217; looks at one of the major problems in the world today &#8211; that old vexed question of what is going on. Is there still time to confront it, let alone solve it, or is it too late? What are the figures, what are the facts, what do people mean [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=268&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.ibras.dk/montypython/episode12.htm#2">Presenter     Good evening. Tonight &#8216;Spectrum&#8217; looks at one of the major problems in the world today &#8211; that old vexed question of what is going on. Is there still time to confront it, let alone solve it, or is it too late? What are the figures, what are the facts, what do people mean when they talk about things? Alexander Hardacre of the Economic Affairs Bureau.<br />
Cut to equally intense pundit in front of a graph with three different coloured columns with percentages at the top. He talks with great authority.<br />
Hardacre     In this graph, this column represents 23% of the population. This column represents 28% of the population, and this column represents 43% of the population. </a></em></p>
<p>One of the irritating things about writing programs is that, often, when you type your program in perfectly, it still doesn&#8217;t work.   You&#8217;ve got bugs!  (Apparently, <a href="http://en.wikipedia.org/wiki/File:H96566k.jpg">one of the first errors in the operation of a computer occurred because a moth got stuck in amongst the componentry</a>. Its removal thus started the act of debugging computer programs.)</p>
<p>The good news is that, in every tutorial I&#8217;ve done on this blog I have had at least one, and often many, bugs in the programs I&#8217;ve written &#8211; even the ones which are only 2 or 3 lines long!!!!  Getting things wrong is a natural part of writing programs.  We need to know how to get things right after they are wrong.  So in this tutorial I wanted to talk about bugs and debugging and things to look for when trying to get your programs running.</p>
<p>The two main causes of bugs we&#8217;re going to look at are <a href="http://en.wikipedia.org/wiki/Syntax">syntax</a> errors and logical errors.</p>
<p><strong>Syntax errors</strong></p>
<p>A syntax error means that you&#8217;ve said something to the computer which doesn&#8217;t make grammatical sense.  Thus, if you were to say to your sibling, &#8220;Yesterday I the car,&#8221; they&#8217;d have absolutely no idea what you were talking about.  That&#8217;s because this sentence doesn&#8217;t fit with English rules of grammar (it lacks a verb).   Similarly, Python programs have their own &#8220;grammar&#8221;.  If you deviate from that grammar the Python interpreter is unable to work out what you mean.</p>
<p>Often a syntax error is caused by a single typo somewhere in the code.  Here are some examples:</p>
<pre>&gt;&gt;&gt; def aFunction
File "&lt;stdin&gt;", line 1
def aFunction
^
SyntaxError: invalid syntax</pre>
<p>Can you see here that the interpreter is trying to tell you where the problem is?  The caret ^ shows where Python thinks that there is a problem.  The interpreter is not always right, but this is a good place to start.</p>
<pre>&gt;&gt;&gt; def aFunction()
File "&lt;stdin&gt;", line 1
def aFunction()
^
SyntaxError: invalid syntax</pre>
<p>First, the interpreter expects a function to have a list of parameters, so is looking for a pair of parentheses -&gt; (). Then, it also expects to see a colon -&gt; : to mark where the function&#8217;s code starts.</p>
<pre>&gt;&gt;&gt; def aFunction()<span style="color:#ff6600;">:</span>
...
File "&lt;stdin&gt;", line 2

^
IndentationError: expected an indented block</pre>
<p>Here, the interpreter sees that you&#8217;ve tried to define a function, but hasn&#8217;t found any code for the function.  Code for a function is indented, hence, if it&#8217;s not there, the interpreter thinks that there&#8217;s a problem with the indentation.</p>
<pre>&gt;&gt;&gt; def aFunction():
...   print "this is a function"
...</pre>
<p>Note that you need to press return on a blank line to finish the function&#8217;s definition if you are in the interpreter.  This is not the case if you are using a text file for your program. Leaving out a colon or having the wrong indentation are perhaps two of the most frequent syntax errors.   As a refresher, Python uses indentation to mark off code blocks.  This means that all the code which is to be executed at the same code level must be indented to the same indent level.  There is no &#8220;right&#8221; level of indentation, as long as the indentation is consistent.   So these are both ok:</p>
<pre>&gt;&gt;&gt; def aFunction():
...   print "First line of code"
...   print "second line of code"
...
&gt;&gt;&gt; def bFunction():
...      print "first line of code"
...      print "second line of code"
...
&gt;&gt;&gt; aFunction()
First line of code
second line of code
&gt;&gt;&gt; bFunction()
first line of code
second line of code</pre>
<p>However, the function below won&#8217;t work because the level of indents (ie the number of spaces before the text starts) is different for each line within the same code block.  A code block is (always? &lt;- not sure) marked off by a colon : in the previous line.</p>
<pre>&gt;&gt;&gt; def cFunction():
...     print "first line of code"
...        print "second line of code"
File "&lt;stdin&gt;", line 3
print "second line of code"
^
IndentationError: unexpected indent</pre>
<p>Where you have a function you need to pass it the right number of arguments:</p>
<pre>&gt;&gt;&gt; range()
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: range expected at least 1 arguments, got 0

&gt;&gt;&gt; range(3)
[0, 1, 2]</pre>
<p>The range() function is interesting in that it can take between 1 and 3 arguments (the second and third arguments are optional).  However if you pass no arguments, or more than 3, then the interpreter will complain to you.</p>
<p><strong>Logical Errors</strong></p>
<p>Logical errors are usually harder to diagnose.  When you write the program, because you have used the right syntax, the Python interpreter doesn&#8217;t tell you that there&#8217;s an error.  Nevertheless, when you run it, you get the wrong answer or the program crashes half way through.  Logical errors often happen with loops, for example, where you forget that the range() function starts at zero, or you have got some other offset incorrect.  They can also happen where you use a function, but don&#8217;t understand what it does, or what output it is supposed to produce.</p>
<p>When faced by a logical error, the usual way to debug is to break down the program into different components and to inspect each in turn.   When you&#8217;re more advanced, you can put logging messages into the code and Python will log the progress of the program to a separate log file.  For the time being however, the easiest thing to do is to put a print statement in.  You put a number of print statements in and sooner or later one of them will print the wrong thing.  Then you know that the error is before that print statement, but after the previous one.</p>
<p>Others</p>
<p>Usually if you make a mistake it will show up as one of these two errors.  However, sometimes you&#8217;ve just made a typing mistake but haven&#8217;t realised it &#8211; like typing * instead of + somewhere.</p>
<h3>Lastly and Most Importantly &#8211; Talk to your Teddy<a href="http://python4kids.files.wordpress.com/2011/06/tux.jpg"><img class="alignright size-medium wp-image-282" title="You can also talk to a Tux" src="http://python4kids.files.wordpress.com/2011/06/tux.jpg?w=294&#038;h=300" alt="" width="294" height="300" /></a></h3>
<p>I&#8217;ve left the most important bit to last.  When you have a debugging problem that you really just can&#8217;t solve, get your teddy bear (I&#8217;m serious, get your bear), bring it to the monitor and explain (in words, out loud) to your teddy what the problem is and why it isn&#8217;t working.</p>
<p>This is a sure-fire, clinically proven way to solve whatever debugging problem you have.  As I mentioned earlier, I&#8217;m absolutely serious about sitting your teddy down beside you and talking (with your voice, not in your head) to it. Now, it doesn&#8217;t absolutely have to be a teddy.  It could be a Lego figure, or an action figure, a parent or a sibling (if they&#8217;re willing) or even a balloon with a face and ears drawn on in pen.</p>
<p>The important thing is that you explain aloud in words what the problem is, because that helps you identify it for yourself.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/268/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=268&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/06/25/talk-to-your-teddy-debugging/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/06/tux.jpg?w=294" medium="image">
			<media:title type="html">You can also talk to a Tux</media:title>
		</media:content>
	</item>
		<item>
		<title>Review, Formatting Silly Sentences</title>
		<link>http://python4kids.wordpress.com/2011/06/14/review-formatting-silly-sentences/</link>
		<comments>http://python4kids.wordpress.com/2011/06/14/review-formatting-silly-sentences/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 08:55:01 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=265</guid>
		<description><![CDATA[Voice Over     Well it&#8217;s a straight fight here at Leicester&#8230;On the left of the Returning Officer (camera shoes grey-suited man) you can see Arthur Smith, the Sensible candidate and his agent, (camera pans to silly people) and on the other side is the silly candidate Jethro Walrustitty with his agent and his wife. Officer [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=265&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode19.htm#13">Voice Over     Well it&#8217;s a straight fight here at Leicester&#8230;On the left of the Returning Officer (camera shoes grey-suited man) you can see Arthur Smith, the Sensible candidate and his agent, (camera pans to silly people) and on the other side is the silly candidate Jethro Walrustitty with his agent and his wife.<br />
Officer     Here is the result for Leicester. Arthur J. Smith&#8230;<br />
Voice Over     Sensible Party<br />
Officer     30,612&#8230;<br />
Jethro Q. Walrustitty&#8230;<br />
Voice Over     Silly Party<br />
Officer     32,108.</a></p>
<p>We have been covering lots of new concepts very quickly. So now is the time to slow down a bit and go over some of the things we&#8217;ve already done, to have a look at them in a little more depth. In particular I want to try to give you some direction on how to make these code samples your own.</p>
<p>I also noticed that I did some things in the last tute which we haven&#8217;t encountered yet.  In particular, I:</p>
<ul>
<li>assigned a function to an object r = random.randint.  Isn&#8217;t Python neat?  You can make these assignments, then the name r points at the function random.randint, so you can use r wherever you use the function.  Sometimes you can use this pattern to make your program run faster (honest!).  However, it might be confusing so I&#8217;ll stop it now!</li>
<li>used tab characters to format a print out: &#8216;\t&#8217;.  There are some &#8220;control&#8221; characters which modify the usual output of a set of printed characters.  Of particular interest are &#8216;\n&#8217; (which makes a new line) and &#8216;\t&#8217; which adds  a tab space. Try printing some <em>strings</em> with \n and \t in them to see what they do.</li>
</ul>
<p>In this tutorial we&#8217;re going to look at <a href="http://docs.python.org/library/stdtypes.html#string-formatting">formatting strings</a>. In the previous tute we constructed a <em>string</em> by adding (using the &#8216;+&#8217; <em>operator</em>) them together. Building <em>strings</em> this way can be a little challenging. Another way to do it, is to use formatting strings. We put place markers into a string, and match the place markers with values to go in there. The place markers are identfied by a % sign in the string, and values are added at the end after  a % sign. Here is a simple example:</p>
<pre>&gt;&gt;&gt; print '%s'%'hi'
hi</pre>
<p>The <em>string</em> &#8216;hi&#8217; is inserted in place of the <em>%s</em> (<em>%s</em> (the s is important &#8211; not just the % by itself) says insert a <em>string</em> here).  There are a number of different options for formatting other than %s (eg %f) but we&#8217;re not going into them here.  <a href="http://docs.python.org/library/stdtypes.html#string-formatting">Read the documentation for more details</a>.</p>
<pre> &gt;&gt;&gt; print '-&gt;%s&lt;-'%'This is the value which is inserted'
 -&gt;This is the value which is inserted&lt;-</pre>
<p>We can define the format string and the value differently:</p>
<pre>&gt;&gt;&gt; formatString="...tell that to the young people of today, and %s."
&gt;&gt;&gt; print formatString%"they won't believe you"
...tell that to the young people of today, and they won't believe you.</pre>
<p>Then you can use the same format string with a different value.  This is useful when you have to print something repetitive, where only a part of it changes:</p>
<pre>&gt;&gt;&gt; print formatString%"they will fall about laughing"
 ...tell that to the young people of today, and they will fall about laughing.</pre>
<p>You can put multiple values into the format string, but the values you supply must:</p>
<ul>
<li>be in brackets ()  (this makes a thing called a <em>tuple, </em>but we haven&#8217;t seen them yet); and</li>
<li>have a comma between each of the values; and</li>
<li>there must be the same number of values as there are %s in the format string.</li>
</ul>
<pre>So, in the previous tute, we might have done something like this:
 &gt;&gt;&gt; formatString="%s x %s = %s"
 &gt;&gt;&gt; print formatString%(2,2,4)
 2 x 2 = 4</pre>
<p>We can also pass variables to be printed as values to the formatting string:</p>
<pre> &gt;&gt;&gt; i=2
 &gt;&gt;&gt; j=3
 &gt;&gt;&gt; print formatString%(i,j,i*j)
 2 x 3 = 6</pre>
<p>So here&#8217;s the times table again:</p>
<pre> &gt;&gt;&gt; for i in range(12):
 ...    for j in range(12):
 ...       print formatString%(i+1,j+1,(i+1)*(j+1))</pre>
<p><strong>Silly Sentences</strong></p>
<p>Let&#8217;s adapt the silly sentence example from last tutorial.<br />
<strong> Set up:</strong><br />
1. open your text editor,<br />
2. open a new file<br />
3. &#8220;save as&#8221; this empty file with the name &#8220;sillySentences110614.py&#8221;, save it in the p4k directory we&#8217;ve created to hold our stuff.</p>
<p>Now copy and paste this:</p>
<pre>import random
nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"]
verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"]
v = len(verbs)-1
n = len(nouns)-1
numberOfSillySentences = 10
formatString = "I was very taken aback when Mrs Pepperpot %s my %s."

for i in range(numberOfSillySentences):
    verb = verbs[random.randint(0,v)]
    noun = nouns[random.randint(0,n)]
    print formatString%(verb,noun)</pre>
<p>And save the file.  Can you see how much easier it is to get the spacing right?</p>
<p>Run the file by going to a console and typing:</p>
<pre>&gt; python sillySentences110614.py</pre>
<p>Funny?</p>
<p>Now you need to make this code your own.</p>
<p><strong>Exercise</strong>: First, change some of the verbs and nouns. You will see the pattern &#8211; for verbs you need to substitute doing words, and they need to be in the past &#8211; ate rather than eat.  For nouns you need to substitute words which name things.   Save the file, then run the program again from the console with:</p>
<pre>&gt; python sillySentences110614.py</pre>
<p>Next, we&#8217;re going to change it to add some feelings in, but you have to supply the feelings:</p>
<p><strong>Exercise:</strong> add some feeling words to the feelings arrray and run again:</p>
<pre>import random
nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"]
verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"]
<span style="color:#ff0000;">feelings=["very taken aback","very happy","quite sad"] # add more feelings to the array here </span>
v = len(verbs)-1
n = len(nouns)-1
<span style="color:#ff0000;">f = len(feelings)-1 </span>
numberOfSillySentences = 10
formatString = "I was <span style="color:#ff0000;">%s</span> when Mrs Pepperpot %s my %s."

for i in range(numberOfSillySentences):
  verb = verbs[random.randint(0,v)]  # choose a verb,noun, feeling  by calculating a random integer
  noun = nouns[random.randint(0,n)]  # between 0 and v,n,f (number of verbs,nouns, feelings)
  <span style="color:#ff0000;">feeling = feelings[random.randint(0,f)] </span> 
  print formatString%(<span style="color:#ff0000;">feeling</span>,verb,noun)  # substitute into the format string and print</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/265/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=265&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/06/14/review-formatting-silly-sentences/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Making this Code Your Own</title>
		<link>http://python4kids.wordpress.com/2011/06/02/making-this-code-your-own/</link>
		<comments>http://python4kids.wordpress.com/2011/06/02/making-this-code-your-own/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 06:26:00 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=253</guid>
		<description><![CDATA[Shopkeeper No, I&#8217;m afraid not actually guv, we&#8217;re fresh out of parrots. I&#8217;ll tell you what though &#8230; I&#8217;ll lop its back legs off, make good, strip the fur, stick a couple of wings on and staple on a beak of your own choice. (taking small box and rattling it) No problem. Lovely parrot. While [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=253&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode10.htm#8"><em>Shopkeeper <span id="Michael">No, I&#8217;m afraid not actually guv, we&#8217;re fresh out of parrots. I&#8217;ll tell you what though &#8230; I&#8217;ll lop its back legs off, make good, strip the fur, stick a couple of wings on and staple on a beak of your own choice. (taking small box and rattling it) No problem. Lovely parrot. </span></em><br />
</a></p>
<p>While I&#8217;ve been giving you coding examples, I&#8217;ve assumed that generalising from them will be self evident.  I understand that that it is not.  In this tutorial we will look at ways of approaching the code with a view to giving you some guidance on how to make this code your own.</p>
<p>The first step is to be able to break the code down into logical units, and then to break those units into subunits.   The second step, once you have broken the code down, is to understand what each of the parts of the code is doing.  If you don&#8217;t know what the pieces are doing, it&#8217;s hard to change what they&#8217;re doing!  The final thing is this:</p>
<p style="padding-left:30px;">try, try, try</p>
<p>and:</p>
<p style="padding-left:30px;">take notice of what happens when you try, try, try.  Python tries to explain why things didn&#8217;t work like you thought they would.  Often you&#8217;ve just mistyped something.</p>
<p>Remember this: there is no reason why you can&#8217;t be a good programmer, even at a young age.</p>
<p>Remember this also: in all of these tutes there is code which I don&#8217;t get right the first time, or have to retype for some reason.</p>
<p>Let&#8217;s take an example:</p>
<pre>&gt;&gt;&gt; for i in range(10):
...     print i
...
0
1
2
3
4
5
6
7
8
9</pre>
<p>This code has two lines, and two parts.  The first part (<em>for i in range (10)</em>) creates a loop.  The second part (<em>print i</em>) does something each time the loop executes.   Next I break the first part down and ask what <em>range()</em> does.   If you don&#8217;t know, use <em>help</em> (in my console this gets &#8220;paged&#8221;, if this happens to you, press &#8216;q&#8217; when you&#8217;re finished reading it):</p>
<pre>&gt;&gt;&gt; help(range)
Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -&gt; list of integers

    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.</pre>
<p>Based on the <em>help</em> file, <em>range()</em> gives us a <em>list</em> (of integers). <a href="http://python4kids.wordpress.com/2010/07/02/if-it-wasnt-for-the-range/">Range tute is here</a>.</p>
<p>Next, I confirm that I understand what it does by trying a concrete example:</p>
<pre>&gt;&gt;&gt; print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
<p>What the <em>for</em> statement does is makes the variable <em>i</em> point to each of these elements in turn (see the print out above).  So, how could we change this? Well, we could either change how the code is looping, or what it is doing in the loop.  Let&#8217;s change what it is doing:</p>
<pre>&gt;&gt;&gt; for i in range(10):
...   print <span style="color:#ff6600;">10-i </span>...
10
9
8
7
6
5
4
3
2
1</pre>
<p>Now, instead of counting up, the loop counts down.  Let&#8217;s change the loop to be a multiplication table:</p>
<pre>&gt;&gt;&gt; for i in range(10):
...   print <span style="color:#ff6600;">"7 x ",</span>i<span style="color:#ff6600;">," = ",7*i</span>
...
7 x  0  =  0
7 x  1  =  7
7 x  2  =  14
7 x  3  =  21
7 x  4  =  28
7 x  5  =  35
7 x  6  =  42
7 x  7  =  49
7 x  8  =  56
7 x  9  =  63</pre>
<p>Note: We need to use a comma (,) here in the print statement because <em>i</em> is a number and <em>&#8220;7 x</em> &#8221; (etc) is a string.</p>
<p><strong>Exercise</strong>: what would we need to change to make this give the times table for 7&#215;1 through to 7&#215;12?</p>
<p><strong>Solution:</strong></p>
<p>In order to start at 1, we need to add 1 to i.  Further for it to run to 12, we need to increase the range by 2:</p>
<pre>&gt;&gt;&gt; for i in range(10<span style="color:#ff6600;">+2</span>):
...   print "7 x ",i<span style="color:#ff6600;">+1</span>," = ",7*<span style="color:#ff6600;">(</span>i<span style="color:#ff6600;">+1)</span> # increase each i and put brackets in otherwise you'll get 1+ 7 x i
...
7 x  1  =  7
7 x  2  =  14
7 x  3  =  21
7 x  4  =  28
7 x  5  =  35
7 x  6  =  42
7 x  7  =  49
7 x  8  =  56
7 x  9  =  63
7 x  10  =  70
7 x  11  =  77
7 x  12  =  84</pre>
<p><strong>Exercise</strong>: How would you change this to print out the times table for all numbers from 1 through 12?</p>
<p><strong>Solution:</strong></p>
<pre>&gt;&gt;&gt; <span style="color:#ff6600;">for i in range(12): </span>...   for j in range(12):
...     print <span style="color:#ff6600;">i+1,"x",j+1," = ",(i+1)*(j+1)</span>  # note the brackets
... <span style="color:#ff6600;">  print </span>  # just to make it more readable - try it without the print statement
[output omitted]</pre>
<p>What I&#8217;ve done here is create two loops, one runs inside the other.  The print out will show you how i and j change in each loop.  See how it looks if you swap i and j in the first two lines:</p>
<pre>&gt;&gt;&gt; for <span style="color:#ff6600;">j</span> in range(12):
...   for <span style="color:#ff6600;">i</span> in range(12):
...     print i+1,"x",j+1," = ",(i+1)*(j+1)
...   print
...
[output omitted]</pre>
<p>You can see that there&#8217;s an issue here with the length of the output.  So, let&#8217;s print two tables each time through the loop, and loop half as many times:</p>
<pre>&gt;&gt;&gt; for i in range(<span style="color:#ff6600;">6</span>):
...   for j in range(12):
...     print i+1,"x",j+1," = ",(i+1)*(j+1)<span style="color:#ff6600;">,'\t\t',i+7,"x",j+1," = ",(i+7)*(j+1) </span>
...   print</pre>
<p>Now, I think that that middle of the loop looks cumbersome.  How about we simplify it by making a function:</p>
<pre>&gt;&gt;&gt; def xByy(x,y):
...   ''' given two numbers x and y, return a string
...       representing their product.  So, for example
...       for 3 and 4, this function returns a string:
...       "3 x 4 = 12"
...   '''
...   return str(x)+" x "+str(y)+" = "+str(x*y) # x and y are numbers so they need to be converted to strings first - str()
...</pre>
<p>Test the function to see it works as you think it should:</p>
<pre>&gt;&gt;&gt; print xByy(3,4)
3 x 4 = 12</pre>
<p>(3&#215;4 <strong>is</strong> 12 isn&#8217;t it?)  Note, help works even on this newly created function &#8211; Try <em>help(xByy)</em></p>
<p>Now we can &#8220;refactor&#8221; the code we had earlier:</p>
<pre>&gt;&gt;&gt; for i in range(6):
...   for j in range(12):
...     print <span style="color:#ff6600;">xByy(i+1,j+1)+'\t\t'+xByy(i+7,j+1)</span> # So, i+1 becomes x and j+1 is y, then i+7 and j+1
...   print</pre>
<p>We could change it again to print more of the tables on a line:</p>
<pre>&gt;&gt;&gt; for i in range(<span style="color:#ff6600;">4</span>):
...   for j in range(12):
...     print xByy(i+1,j+1)+'\t\t'+xByy(i+<span style="color:#ff6600;">5</span>,j+1)<span style="color:#ff6600;">+'\t\t'+xByy(i+9,j+1)</span># Adding another column
...   print</pre>
<p>And so on.   The other thing we could do is recognise that <em>range()</em> is a<em> list</em> just like any other, so we could equally see what would happen if we used another list:</p>
<pre>&gt;&gt;&gt; names = ["John","Eric", "Terry","Graham","Terry","Michael","Carol","Connie","Ian"]
&gt;&gt;&gt; for n in names:
...    print n
...
John
Eric
Terry
Graham
Terry
Michael
Carol
Connie
Ian</pre>
<p>Realising this you could mix things up a little:</p>
<pre>&gt;&gt;&gt; import random
&gt;&gt;&gt; r = random.randint  # You haven't seen this before, it is me cheating a little to save on typing.
&gt;&gt;&gt; nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"]
&gt;&gt;&gt; verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"]
&gt;&gt;&gt; v = len(verbs)-1
&gt;&gt;&gt; n = len(nouns)-1
&gt;&gt;&gt; for i in range(10):
...   print "I was very taken aback when Mrs Pepperpot "+verbs[r(0,v)]+" my "+nouns[r(0,n)]+"."
...
I was very taken aback when Mrs Pepperpot infuriated my letterbox.
I was very taken aback when Mrs Pepperpot smelled my pumpernickel.
I was very taken aback when Mrs Pepperpot forgot my pencil.
I was very taken aback when Mrs Pepperpot smelled my toy car.
I was very taken aback when Mrs Pepperpot tripped over my house.
I was very taken aback when Mrs Pepperpot played my toy car.
I was very taken aback when Mrs Pepperpot lost my house.
I was very taken aback when Mrs Pepperpot forgot my pillow.
I was very taken aback when Mrs Pepperpot dropped my pumpernickel.
I was very taken aback when Mrs Pepperpot erased my house.</pre>
<p><strong>Exercise</strong>: What is going on here?  Why have I assigned, <em>v = len(verbs)-1</em>? etc?</p>
<p><strong>Note</strong>: <em>r(0,v)</em> is shorthand for <em>random.randint(0,v)</em></p>
<p>You can run this with a different <em>list</em> of verbs and nouns, just make sure, after you assign or change the verbs/nouns <em>list</em> that you reassign the values of <em>v</em> and <em>n</em>.</p>
<p><strong>Exercise:</strong> change this code so that you have a list of feelings one of which is inserted at random &#8211; I was very x&#8230;.</p>
<p><strong>Final note: Syntax Errors</strong></p>
<p>Often things will fail because you have a syntax error, which is computer speak for &#8220;you have made a typo&#8221;.  It is usually just a case of working through what you did to find the mistake.</p>
<p><strong>Examples:</strong></p>
<p><em>TypeError: &#8216;list&#8217; object is not callable</em> &#8211; this probably means you&#8217;ve used round brackets () when you were supposed to use square ones []</p>
<p><em>NameError: name &#8216;some_text&#8217; is not defined</em> &#8211; this probably means you are missing inverted commas around something which is meant to be a string &#8220;some_text&#8221;</p>
<p><em>TypeError: cannot concatenate &#8216;str&#8217; and &#8216;int&#8217; objects</em> &#8211; you&#8217;ve tried to add a string and a number.  Convert the number to a string using str().</p>
<p><strong>Conclusion</strong></p>
<p>We&#8217;ve played around here with some basic building blocks of the language and found we can do some interesting stuff.  We have been able to vary things by breaking the parts of the program down into pieces, understanding what the pieces do, and, based on that understanding, changing them.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/253/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=253&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/06/02/making-this-code-your-own/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>A Functioning Stand Alone Python Program</title>
		<link>http://python4kids.wordpress.com/2011/05/17/a-functioning-stand-alone-python-program/</link>
		<comments>http://python4kids.wordpress.com/2011/05/17/a-functioning-stand-alone-python-program/#comments</comments>
		<pubDate>Tue, 17 May 2011 02:01:21 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=239</guid>
		<description><![CDATA[Interviewer:     The Magna Carta &#8211; was it a document signed at Runnymede in 1215 by King John pledging independence to the English barons, or was it a piece of chewing gum on a bedspread in Dorset? The latter idea is the brainchild of a man new to the field of historical research. Mr Badger, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=239&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode32.htm#8"><em>Interviewer:     The Magna Carta &#8211; was it a document signed at Runnymede in 1215 by King John pledging independence to the English barons, or was it a piece of chewing gum on a bedspread in Dorset? The latter idea is the brainchild of a man new to the field of historical research. Mr Badger, why &#8211; why are you on this programme?</em><br />
<em>[Pull back to show Mr Badger. He wears a flat cap and has a Scots accent.]</em><br />
<em>Badger:     Well, I think I can answer this question most successfully in mime. (mimes incomprehensibly)</em></a></p>
<p>In the last tutorial we created a file using our text editor and saved a function to it.  This file was called trivia.py and in it was the <em>module</em> &#8220;trivia&#8221;.  We then started Python in a console and <em>import()</em>ed the trivia <em>module. </em> Once <em>imported</em>, it created a<em> &#8220;namespace&#8221;</em> and we could access the <em>askQuestion()</em> function from within the trivia <em>namespace</em> by using a dot &#8211; <em>trivia.askQuestion()</em>.  In order for the module to work properly we had to include an <em>import</em> statement within the <em>module</em> itself so that everything that the <em>module</em> relied upon was <em>imported</em> within the <em>module. </em> We then manually loaded our data from a <em>pickle</em> file we created and, manually, ran the <em>askQuestion()</em> function on the first question in our data store.   Finally we added <em>docstrings</em> to the function and the module.</p>
<p>In this tutorial we&#8217;re going to try to do much the same thing again, but without using the Python interpreter.  That is, we will need to take the things we did in the interpreter and implement them in our trivia.py file.  We will have a functioning (although still quite simple) stand alone Python program.</p>
<p>To start, open up trivia.py in your text editor.<br />
Looking at the last tute, we can see that we used the <em>cPickle</em> <em>module,</em> so that will need to be <em>import</em>ed.  We then opened the existing pickle file, and loaded the stored pickle.</p>
<p>So, first, edit the file to add <em>import cPickle</em> after <em>import random</em>:</p>
<pre>import random
import cPickle</pre>
<p>Next, let&#8217;s add a &#8216;constant&#8217;[1] to store our the filename of our <em>pickle</em> file.  Constants are not really all that constant in Python, in that Python will let us change their value later if we choose.  However, by convention, if you name a variable with all caps, then it is assigned a value only once (usually at the start of the program).  Add this after the <em>imports</em> but before the first definition:</p>
<pre>QUESTIONS_FILENAME = 'p4kTriviaQuestions.txt'</pre>
<p>Now, we add some code to load the questions into an array.  In theory, this code could go anywhere in the file after the variable QUESTIONS_FILENAME has been given a value.  However, it&#8217;s better if we put it at the end of the file after the function definition.  It should not be indented (remember that Python identifies code blocks by indentation):</p>
<pre>fileObject = open(QUESTIONS_FILENAME,'r')  # note: 'r' for read
questionsList = cPickle.load(fileObject)  # load the questions
fileObject.close()   # finished reading, so close the file</pre>
<p>If you go back through the previous tutes (eg <a href="http://python4kids.wordpress.com/2011/05/02/baby-steps-with-our-text-editor/">the previous tute</a>) you&#8217;ll see that this is the same code we used in the interpreter.   This shouldn&#8217;t be surprising because Python runs the code in this program as if it was being typed into the interpreter.[2]  Now that the questions have been loaded, let&#8217;s iterate through each of them, asking them in turn:</p>
<pre>for question in questionsList:
    askQuestion(question)  
    # note, that because we're within the module we can just
    # use the function's name directly without being qualified by the
    # trivia namespace.  If you put trivia.askQuestion, the code would not work.</pre>
<p>Save the file [see below for what the code should look like], then go to a console/command line &#8211; ie the thing from which you have run the Python interpreter in earlier tutes.  Do not run the interpreter itself. Rather, we run the file by typing the following and pressing the &#8216;enter&#8217; or &#8216;return&#8217; key:</p>
<pre>&gt; python trivia.py
Who expects the Spanish Inquisition?
0 .  Brian
1 .  Eric the Hallibut
2 .  An unladen swallow
3 .  Nobody
4 .  Me!
Enter the number of the correct answer: 3
Correct! Hooray!
What is the air-speed velocity of an unladen swallow?
0 .  23.6 m/s
1 .  10 m/s
2 .  14.4 m/s
3 .  What do you mean? African or European swallow?
Enter the number of the correct answer: 3
Correct! Hooray!
Is this the right room for an argument?
0 .  Down the hall, first on the left
1 .  No
2 .  I've told you once
3 .  Yes
Enter the number of the correct answer: 2
Correct! Hooray!</pre>
<p>Note that this is from the <span style="text-decoration:underline;">command line</span> &#8211; not the Python interpreter.  You can tell because there is only one &gt; (you might have something different as your &gt; thingamy) where the interpreter has three &gt;&gt;&gt;</p>
<p>As you can see the two lines:</p>
<pre>for question in questionsList:
    askQuestion(question)</pre>
<p>Cause the program it iterate through each element in the list <em>questionsList</em> and, for each element, to call the <em>askQuestion()</em> function with that element as a parameter.  If you remember, each of these elements is, itself, a list.</p>
<p><strong>Homework: </strong> think about how we would need to change this program to keep track of the player&#8217;s score</p>
<p><strong>Bonus points:</strong> actually change the program so that it keeps track of the player&#8217;s score and prints out the score after all questions have been asked.</p>
<p><strong>Notes:</strong></p>
<p>1.  Technically, in the <strong></strong>code:</p>
<p style="padding-left:30px;"><em>QUESTIONS_FILENAME = &#8216;p4kTriviaQuestions.txt&#8217;</em>,</p>
<p><em>QUESTIONS_FILENAME</em> is a <span style="text-decoration:underline;"><em>variable,</em></span> and<em> &#8216;p4kTriviaQuestions.txt&#8217;</em> is the <span style="text-decoration:underline;"><em>constant</em></span><em>.</em>  However, in the text I&#8217;m referring to the variable as if it was the constant.<strong><br />
</strong></p>
<p>2.  Actually, when you run a program from the command line Python reads the whole file and pre-compiles it first (or uses an existing pre-compiled version if you haven&#8217;t changed the file) then runs the pre-compiled version.  Have a look for file called trivia.pyc in your directory.</p>
<p><strong>Source Code</strong></p>
<p>The complete file should look like this:</p>
<pre>'''
The place for a doctring which was an exercise for you to complete in the previous tute.
'''

import random
import cPickle

QUESTIONS_FILENAME = 'p4kTriviaQuestions.txt'

def askQuestion(questionList):
    '''
    Given a question in a form of a list, with the first entry being the question,
    the next entry being the correct answer to the question and one or more other
    entries, each of which is an incorrect answer, pose the question, randomising the
    answers and test whether the answer is correct
    '''
    question = questionList[0]
    answers = questionList[1:]
    numberOfAnswers = len(answers)-1
    # -1 because the first entry in the list is number 0
    correctAnswer = random.randint(0, numberOfAnswers)
    # choose an answer at random
    # then swap it with the correct answer
    spam = answers[correctAnswer]
    answers[correctAnswer] = answers[0]
    answers[0] = spam
    print question
    for i in range(len(answers)):
        print i,'. ',answers[i]
    answer = raw_input('Enter the number of the correct answer: ')
    if answer == str(correctAnswer):
        print 'Correct! Hooray!'
    else:
        print 'Wrong...'

fileObject = open(QUESTIONS_FILENAME,'r')  # note: 'r' for read
questionsList = cPickle.load(fileObject)  # load the questions
fileObject.close()   # finished reading, so close the file

for question in questionsList:
    askQuestion(question)  
    # note, that because we're within the module we can just
    # use the function's name directly without being qualified by the
    # trivia namespace.</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/239/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=239&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/05/17/a-functioning-stand-alone-python-program/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Baby Steps with Our Text Editor</title>
		<link>http://python4kids.wordpress.com/2011/05/02/baby-steps-with-our-text-editor/</link>
		<comments>http://python4kids.wordpress.com/2011/05/02/baby-steps-with-our-text-editor/#comments</comments>
		<pubDate>Mon, 02 May 2011 23:26:54 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=226</guid>
		<description><![CDATA[Second Interviewer     I didn&#8217;t really call you Eddie-baby, did I, sweetie? Ross     Don&#8217;t call me sweetie!! Second Interviewer     Can I call you sugar plum? In this tutorial we&#8217;re going to start using the power of the text editor that I&#8217;ve been badgering you about over the last few tutorials.  We are going [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=226&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode01.htm#5"><em>Second Interviewer     I didn&#8217;t really call you Eddie-baby, did I, sweetie?</em><br />
<em>Ross     Don&#8217;t call me sweetie!!</em><br />
<em>Second Interviewer     Can I call you sugar plum?</em></a></p>
<p>In this tutorial we&#8217;re going to start using the power of the text editor that I&#8217;ve been badgering you about over the last few tutorials.  We are going to go back to the earlier tutorials and resurrect some of the code there.</p>
<p><strong>Exercise:</strong><br />
Create a new document with your text editor<br />
Save the document to a file called trivia.py  You need to be careful that your text editor doesn&#8217;t add &#8216;.txt&#8217; to the end of the file&#8217;s name as some have the habit of doing.<br />
copy the following function into the file (<a href="http://python4kids.wordpress.com/2010/09/22/trivia-game-part-2/">originally found here</a>, with some comments dropped):</p>
<pre>def askQuestion(questionList):
    question = questionList[0]
    answers = questionList[1:]
    numberOfAnswers = len(answers)-1
    # -1 because the first entry in the list is number 0
    correctAnswer = random.randint(0, numberOfAnswers)
    # choose an answer at random
    # then swap it with the correct answer
    spam = answers[correctAnswer]
    answers[correctAnswer] = answers[0]
    answers[0] = spam
    print question
    for i in range(len(answers)):
        print i,'. ',answers[i]
    answer = raw_input('Enter the number of the correct answer: ')
    if answer == str(correctAnswer):
        print 'Correct! Hooray!'
    else:
        print 'Wrong...'</pre>
<p>save the changes you&#8217;ve just made to the file<br />
It should look something like this (notice the code highlighting in Kate.  A basic text editor like NotePad won&#8217;t do this highlighting for you):</p>
<p><a href="http://python4kids.files.wordpress.com/2011/05/pk4110428-1.png"><img class="aligncenter size-full wp-image-227" title="pk4110428-1" src="http://python4kids.files.wordpress.com/2011/05/pk4110428-1.png?w=630&#038;h=362" alt="" width="630" height="362" /></a></p>
<p>now, start a python prompt from the command line and <em>import</em> the <em>module: </em>(note: for this to work you must be in the same directory as the trivia.py file when you start the Python prompt Google &#8220;cd change directory&#8221; if you have problems)<em><br />
</em></p>
<pre>&gt;&gt;&gt; import trivia
&gt;&gt;&gt; dir(trivia)
['__builtins__', '__doc__', '__file__', '__name__', 'askQuestion']</pre>
<p>Can you see that we&#8217;ve <em>import</em>ed our <em>trivia</em> file at the Python prompt (note: not import trivia.py, Python automatically adds the .py when it&#8217;s looking for the module).  We&#8217;ve used introspection to see its attributes and methods &#8211; you can see the <em>askQuestion()</em> function there.  We can&#8217;t actually ask a question at the moment, because we don&#8217;t have a question to ask, so let&#8217;s recover those we were storing that pickle file from earlier tutes:</p>
<pre>&gt;&gt;&gt; import cPickle
&gt;&gt;&gt; filename = 'p4kTriviaQuestions.txt'
&gt;&gt;&gt; fileObject = open(filename,'r')
&gt;&gt;&gt; triviaQuestions = cPickle.load(fileObject)
&gt;&gt;&gt; fileObject.close()
&gt;&gt;&gt; triviaQuestions
[['Who expects the Spanish Inquisition?', 'Nobody', 'Eric the Hallibut', 'An unladen swallow', 'Brian', 'Me!'], ['What is the air-speed velocity of an unladen swallow?', 'What do you mean? African or European swallow?', '10 m/s', '14.4 m/s', '23.6 m/s'], ['Is this the right room for an argument?', "I've told you once", 'No', 'Down the hall, first on the left', 'Yes']]
&gt;&gt;&gt; triviaQuestions[0]
['Who expects the Spanish Inquisition?', 'Nobody', 'Eric the Hallibut', 'An unladen swallow', 'Brian', 'Me!']</pre>
<p>Now, let&#8217;s get a single question, because that&#8217;s what the <em>askQuestion()</em> function is expecting:</p>
<pre>&gt;&gt;&gt; question = triviaQuestions[0]</pre>
<p>So, in theory we should be ready to run this through our <em>askQuestion()</em> function.  Let&#8217;s try it:</p>
<pre>&gt;&gt;&gt; trivia.askQuestion(question)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "trivia.py", line 6, in askQuestion
    correctAnswer = random.randint(0, numberOfAnswers)
NameError: global name 'random' is not defined</pre>
<p>Uh-oh, it didn&#8217;t work because we haven&#8217;t <em>import</em>ed the <em>random</em> module. Gosh darn it.  Let&#8217;s add that at the start of our file so the first couple of lines now look like this:</p>
<pre>import random

def askQuestion(questionList):
    question = questionList[0]
    answers = questionList[1:]</pre>
<p>Now we go back to the Python command line and import it again:</p>
<pre>&gt;&gt;&gt; import trivia
&gt;&gt;&gt; trivia.askQuestion(question)</pre>
<p>Unfortunately, this also fails exactly as it did before &#8211; even though we know we&#8217;ve <em>import</em>ed the random module.  The reason is that <em>import</em> only happens once.  If you <em>change a module, then import </em>it a second time, it doesn&#8217;t do anything.  However, we can update a module by using the <em>reload()</em> function (you can also exit the Python prompt, restart Python and then <em>import</em>, but <em>reload()</em> is easier).  Once we do that, things start working as we expect them to:</p>
<pre>&gt;&gt;&gt; reload(trivia)
&lt;module 'trivia' from 'trivia.py'&gt;
&gt;&gt;&gt; trivia.askQuestion(question)
Who expects the Spanish Inquisition?
0 .  An unladen swallow
1 .  Eric the Hallibut
2 .  Nobody
3 .  Brian
4 .  Me!
Enter the number of the correct answer: 2
Correct! Hooray!</pre>
<p>So, some things to notice:<br />
* when we <em>import</em>ed our <em>module,</em> we <em>import</em>ed the name of the file less the &#8216;.py&#8217;<br />
* on <em>import</em> it created a<em> &#8216;namespace&#8217;</em> called <em>trivia. </em> The function we defined was in the <em>trivia</em> <em>namespace</em> and we accessed it using a dot: <em>trivia.askQuestion()</em>.  Had we just typed in <em>askQuestion()</em> the computer would not know what we are talking about:</p>
<pre>&gt;&gt;&gt; askQuestion(question)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'askQuestion' is not defined</pre>
<p>We can <em>import</em> functions individually using a different syntax and, if we do, the function&#8217;s name is present in the base <em>namespace</em> and it can be called directly:</p>
<pre>&gt;&gt;&gt; from trivia import askQuestion
&gt;&gt;&gt; askQuestion(question)</pre>
<p>However, doing this is frowned upon because it &#8216;pollutes&#8217; the <em>namespace. </em> In particular, you may end up with collisions between functions imported into the <em>namespace. </em> So if you have two modules, each with the a function of the same name, but of different effect the interpreter would have a problem if you from imported both of them.  Try to avoid using the import from syntax at least until you&#8217;re familiar with why it&#8217;s a problem.</p>
<p>Something our function is missing is a doc string.  Let&#8217;s add one.  Go back to your text editor and edit the function so now it reads:</p>
<pre>def askQuestion(questionList):
    '''
    Given a question in a form of a list, with the first entry being the question,
    the next entry being the correct answer to the question and one or more other
    entries, each of which is an incorrect answer, pose the question, randomising the
    answers and test whether the answer is correct
    '''
    question = questionList[0]
    answers = questionList[1:]</pre>
<p>Save the file<br />
Go to the Python prompt and <em>reload()</em> the module, then look at the docstring:</p>
<pre>&gt;&gt;&gt; reload(trivia)
&lt;module 'trivia' from 'trivia.py'&gt;
&gt;&gt;&gt; print trivia.askQuestion.__doc__

        Given a question in a form of a list, with the first entry being the question,
        the next entry being the correct answer to the question and one or more other
        entries, each of which is an incorrect answer, pose the question, randomising the
        answers and test whether the answer is correct</pre>
<p>Now, the important thing to note is that we were able to change part of the function without retyping all of it.  Going forward we will be able to extend this module by adding bits to it.</p>
<p><strong>Homework:</strong><br />
Create a docstring for the trivia module itself, describing what the trivia module will be doing (make a list of the things you think it should eventually do in order to make a trivia game).  Work out where the docstring needs to go in trivia.py.  Save the file, then reload the module from the Python prompt and print the docstring out.</p>
<p><strong>Homework:</strong><br />
Think about what part of the Python language we might use to ask all of the questions stored in the pickle file, rather than just the first one.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/226/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/226/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/226/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/226/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/226/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/226/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/226/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=226&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/05/02/baby-steps-with-our-text-editor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/05/pk4110428-1.png" medium="image">
			<media:title type="html">pk4110428-1</media:title>
		</media:content>
	</item>
		<item>
		<title>Catching Our Breath</title>
		<link>http://python4kids.wordpress.com/2011/05/02/catching-our-breath/</link>
		<comments>http://python4kids.wordpress.com/2011/05/02/catching-our-breath/#comments</comments>
		<pubDate>Mon, 02 May 2011 12:39:27 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=233</guid>
		<description><![CDATA[Character     Servant ho! He then goes underwater again. The servant in the boat steps into the water and goes under. Cut to announcer, now up to his waist in sea. In this tutorial we review what we have covered over the last few tutorials, and lay some more groundwork for working with files and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=233&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode22.htm#9">Character     Servant ho!<br />
He then goes underwater again. The servant in the boat steps into the water and goes under. Cut to announcer, now up to his waist in sea.</a></p>
<p>In this tutorial we review what we have covered over the last few tutorials, and lay some more groundwork for working with files and using the text editor that you organised in the last tutorial.</p>
<p>In recent tutorials we&#8217;ve learned quite a bit:</p>
<ul>
<li>pickling basics: we learnt about a way of storing data called &#8220;pickling&#8221;. We did some basic pickling. Pickles are a way of storing data. This means that, in our trivia quiz, we&#8217;ll be able to add questions from time to time, without having to retype all of the questions we have added earlier.</li>
<li>pickling data: we took our understanding of pickles and applied it to our data. We saw how we can save the data that we were using for our game into a file for later use.</li>
<li>introspection: Python objects are able to tell you about themselves. In particular we learnt about the .__doc__ string and the dir() functions. Introspection allows us to find out stuff about the program we are working with. In some cases it can be a sort of help file by telling us some stuff about an object. Introspection is part of Python &#8216;for free&#8217;. It is available whenever you run Python without having to (eg) import introspection in the way we imported cPickle.</li>
<li>more on pickles: how to load data that&#8217;s been stored in a file, modify it and dump it back to the file. So we can keep data that our programs rely on in a file. The point of this tutorial was to show how the pickle can be used like a locker for your data. If you put your data into a pickle not only will it be there for you to take out later, but you can take it out, change it, then replace the old data with the new data.</li>
<li>dictionaries. Dictionaries are a little like lists, except you can map a given value to an index. In the homework, your example was to map names of your friends to their favourite game). Unlike lists, which access values by knowing their position in the list, dictionaries access values by giving the value a name, called a &#8216;key&#8217;. In order to use a list, you are dependent upon knowing the order of the items in the list. This can cause problems if you want to change the sort of data stored in the list. In this tutorial we saw that we couldn&#8217;t add an alternative correct answer because there was literally nowhere in our list to store it (because we&#8217;d earlier decided to consider all entries in the list after a certain point to be incorrect answers. Adding an alternative correct answer would invalidate all the existing data (eg every question that you had already written to the pickle file). Because dictionaries access values through keys they do not suffer from this problem. Position is not important for dictionaries. If you have data stored in a dictionary, then to add new categories of answer is a simple question of adding a new key to identify the new category of data; and, finally,</li>
<li>in the most recent tutorial, I told you to go get a text editor and learn the basics of how to use it. Using a text editor will allow us to store the Python code that we are writing in much the same way as we have been saving data in the other tutorials. One of the benefits of this is that we don&#8217;t need to retype code all the time. If we want to modify a function we just open the text editor and modify it &#8211; without having to retype it from scratch.</li>
</ul>
<p>Most of the things we&#8217;ve covered here have to do with files and (therefore) the file system on your computer. In order to do further tutorials we&#8217;re going to be changing the file system, and if we do that we&#8217;ve got a problem in that we may end up deleting or changing something we didn&#8217;t want to. For that reason I&#8217;d like you to talk to a responsible adult and set up a separate folder on your hard drive specifically for these tutorials. Call it python4kids (or p4k if you are a lazy typist).</p>
<p><strong>Homework</strong>: have a responsible adult set up a separate folder (also called a directory) for these tutorials.  Name it python4kids or p4k.</p>
<p><strong>Homework</strong>: work out (ask someone or Google) how to change directory into this new folder so that any files you make are made here. Whenever you run Python change directory to this folder first, so that Python runs in the directory.</p>
<p><strong>Homework</strong>: work out how to load files from this directory using your text editor and how to save files <strong>to this directory</strong> using your text editor.</p>
<p><strong>Homework</strong>: Copy the pickle file we&#8217;ve been working with to this new directory. If you have not made any or many additions to it, you can just recreate it by running the tutorials in the directory.</p>
<p>If you do these things and whenever you do these tutorials you do them in that folder, saving files to that folder, then I don&#8217;t have to worry about accidentally overwriting your other data, because the only data that will be there is data we&#8217;ve created in these tutorials.</p>
<p>In terms of Python language features &#8211; so far we have covered quite a lot of them. We know about:</p>
<ul>
<li>data: strings, numbers (integers), lists and dictionaries</li>
<li>controlling program flow: if/then/else, while, for</li>
<li>some regularly used in built functions: range, len</li>
<li>subroutines: def (functions), modules, import</li>
<li>other language features: objects, introspection</li>
</ul>
<p>There is a big one which is still missing &#8211; classes.  We will get to classes in a few more&#8230; classes. Till then&#8230; do your homework.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/233/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=233&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/05/02/catching-our-breath/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Keeping Code</title>
		<link>http://python4kids.wordpress.com/2011/04/20/keeping-code/</link>
		<comments>http://python4kids.wordpress.com/2011/04/20/keeping-code/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 13:28:42 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=217</guid>
		<description><![CDATA[Well, so far we&#8217;ve learnt about storing data (either &#8220;flat&#8221; in file, or as an object which Python does in pickles which are also data in files, but with some structure) but we don&#8217;t know anything about storing the code we are typing. This means that we need to go through the tedium of typing stuff [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=217&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Well, so far we&#8217;ve learnt about storing data (either &#8220;flat&#8221; in <em>file</em>, or as an <em>object</em> which Python does in <em>pickles</em> which are also data in files, but with some structure) but we don&#8217;t know anything about storing the code we are typing. This means that we need to go through the tedium of typing stuff in all the time (or cutting and pasting I guess).  It  is especially tedious when we mistype something.</p>
<p>In order to do some more complex things in Python we really need to be able to store our code somewhere so that typing mistakes we make don&#8217;t mean we have to re-type the <a href="http://en.wiktionary.org/wiki/kit_and_kaboodle">whole kit and kaboodle</a>. We could, if we really wanted to, open a file from within our Python prompt and write code to the file (as a flat file):</p>
<pre> &gt;&gt;&gt; f = open('textfile.py','w')
 &gt;&gt;&gt; f.write("print 'This is some python code stored in a file'")
 &gt;&gt;&gt; f.close()
 &gt;&gt;&gt; import textfile
 This is some python code stored in a file</pre>
<p>What has happened here is that we&#8217;ve <em>open()</em>ed a file called &#8216;textfile.py&#8217; (again, we&#8217;ve taken the chance that there isn&#8217;t already such a file, because <em>open()</em>ing it would delete the existing contents).  We&#8217;ve then written the following to the file: <em>print &#8216;This is some python code stored in a file&#8217;</em></p>
<p>We can tell what&#8217;s in the file by opening it and reading it back:</p>
<pre>&gt;&gt;&gt; f = open('textfile.py','r')
&gt;&gt;&gt; print f.read()
print 'This is some python code stored in a file'
&gt;&gt;&gt; f.close()</pre>
<p>Then, when we imported the file, the contents of the file were executed [1].  We can execute this file from the command line (not the Python prompt) using the <em>python</em> command:</p>
<pre>&gt;python textfile.py
This is some python code stored in a file</pre>
<p>Note only one &gt;, not three.</p>
<p>Why did we put double quotes? See note 2 below.</p>
<p>Now, using Python to write Python code to a file would be incredibly tedious.  Moreover, it wouldn&#8217;t solve the problem we have with the ease of editing.  So now we&#8217;re going to talk about text editors.  You may need a responsible adult to help you here.</p>
<p>Text editors are programs which are designed to, well, edit text.  They are generally nothing like word processors, and, for our purposes, you can&#8217;t use a word processor as a text editor (see note [3]).  There are way heaps lots of text editors.  Everyone is welcome to list their favourite in comments if they feel inclined.</p>
<p>When you use a text editor, there is a different cycle of work.  To date, feedback has been instant because our code has been typed directly into the Python interpreter.  However, when using a text editor your code must first be saved to a file, then you need to execute the file using the <em>python</em> command.  However, once you&#8217;ve saved a file you can easily modify it and re-run it.  If you mistyped a single character, then you can use the text editor to navigate to that character and change just it, then save the file and run it through the Python interpreter again.</p>
<p>For the following tutes you need to complete these exercises:</p>
<p><strong>Exercise:</strong> See if a text editor is already installed on your computer (try Notepad on Windows, Linux systems should have Gedit and/or Kate)</p>
<p><strong>Exercise</strong>: If you don&#8217;t have a text editor installed, get the permission of a responsible adult, go find a <a href="http://en.wikipedia.org/wiki/List_of_text_editors">text editor</a> and install it on your computer.</p>
<p><strong>Exercise:</strong> Learn how to use it to open files (usually ctrl+O), and save files (usually ctrl+S).</p>
<p><strong>Exercise:</strong> using your new found text editor skills, open a new file and save the following to it:</p>
<pre>print "Hello world!"</pre>
<p>Then, open a command line, <a href="http://en.wikipedia.org/wiki/Cd_%28command%29">cd</a> to the directory in which you saved the file, then run the file by typing <em>python &lt;name of file&gt;</em>.  Find a responsible adult to help if you can&#8217;t work out the cd command.</p>
<p><strong>Hints:</strong></p>
<p>A text editor that I like is called <a href="http://en.wikipedia.org/wiki/Kate_%28text_editor%29">Kate</a>.  Kate needs a windowing system to run, but is available on all popular operating systems. One of the neat things about Kate is that it will do Python syntax highlighting for you.  That is, it will use different colours to show (eg) what are strings, what are commands etc.  Kate also has a command line within the editor, which may make life a little easier for you.  Kate will also automatically indent your code.  This is a useful feature to have and saves you typing in tab characters or spaces to line up code blocks.  This is what the file we saved earlier looks like in Kate, showing code highlighting (the red part shows a string, the black part a command):</p>
<p><a href="http://python4kids.files.wordpress.com/2011/04/p4kkatesshot1.jpg"><img class="aligncenter size-full wp-image-219" title="Screenshot of Kate text editor showing syntax highlighting" src="http://python4kids.files.wordpress.com/2011/04/p4kkatesshot1.jpg?w=630" alt=""   /></a></p>
<p>A basic editor which works on the command line is called <a href="http://www.nano-editor.org/">nano</a>.</p>
<p>If you want to make life hard for yourself, but want to be able to swagger as if you were a Real Programmer(tm) try <a href="http://en.wikipedia.org/wiki/Emacs">emacs</a> or <a href="http://en.wikipedia.org/wiki/Vi">vi</a>.  Warning: don&#8217;t try emacs or vi unless you are brave, neither is for the faint hearted.</p>
<p>There is a text editor which often accompanies Python distributions (it is called idle).  However, at the moment I don&#8217;t want to use idle, because it may cause problems down the track.</p>
<p><strong>Notes:</strong></p>
<p>[1] Python has its own function to execute strings as if they were instructions.  It&#8217;s called exec(), and that&#8217;s happened. Example:</p>
<pre>&gt;&gt;&gt; a = "print 'This is some python code stored in a file'"
&gt;&gt;&gt; a
"print 'This is some python code stored in a file'"
&gt;&gt;&gt; exec(a)
This is some python code stored in a file</pre>
<p><strong>Warning:</strong> there are security issues with using <em>exec()</em> don&#8217;t try this at home.<br />
[2]  That is a bit subtle.  We had to put what was written into a string in order to write it.  We&#8217;ve had to use double quotes to make the command we want stored into a string.  Had we left the double quotes out we would have had a problem:</p>
<pre> &gt;&gt;&gt; f = open('textfile.py','w')
 &gt;&gt;&gt; f.write(print 'This is some python code stored in a file')
 File "&lt;stdin&gt;", line 1
 f.write(print 'This is some python code stored in a file')
 ^
 SyntaxError: invalid syntax</pre>
<p>When we put the double quotes in, it&#8217;s not a command anymore, it&#8217;s just a string, and we can write strings to files.  However, we wanted to write an actual command to the file &#8211; the print command, and for that we needed to use single quotes.  We needed to use double quotes so that the single quotes would be made part of the string.</p>
<p>[3]  If you are careful to use &#8220;save as&#8221; and always choose &#8220;plain text&#8221; as the save format, then you can use a word processor, but they are best avoided.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/217/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=217&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/04/20/keeping-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>

		<media:content url="http://python4kids.files.wordpress.com/2011/04/p4kkatesshot1.jpg" medium="image">
			<media:title type="html">Screenshot of Kate text editor showing syntax highlighting</media:title>
		</media:content>
	</item>
		<item>
		<title>Dictionaries, Hovercraft, Eels</title>
		<link>http://python4kids.wordpress.com/2011/04/06/dictionaries-hovercraft-eels/</link>
		<comments>http://python4kids.wordpress.com/2011/04/06/dictionaries-hovercraft-eels/#comments</comments>
		<pubDate>Wed, 06 Apr 2011 09:05:10 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=209</guid>
		<description><![CDATA[Tobacconist     What? Hungarian     (miming matches) My hovercraft is full of eels. Tobacconist     Matches, matches? (showing some) Dictionaries, Hovercraft, Eels Welcome to the new look site (which, due the wonder of CSS, has been retrospectively applied to all the earlier tutes)!  This was chosen because it was the first template I found which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=209&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode25.htm#2"><em>Tobacconist     What?</em><br />
<em>Hungarian     (miming matches) My hovercraft is full of eels.</em><br />
<em>Tobacconist     Matches, matches? (showing some)</em></a></p>
<p>Dictionaries, Hovercraft, Eels</p>
<p>Welcome to the new look site (which, due the wonder of CSS, has been retrospectively applied to all the earlier tutes)!  This was chosen because it was the first template I found which allowed you to see the whole of the code snippets.</p>
<p>In our earlier tutes we needed to come up with a way to keep track of questions in our trivia game.  We chose to use a <em>list</em> to do that (because that was the only data structure we knew of), but there was another option open to us &#8211; a <em>dictionary:</em></p>
<pre>&gt;&gt;&gt; aDictionary = {}
&gt;&gt;&gt; aDictionary
{}</pre>
<p>What this code does is create a <em>dictionary</em> which is empty.  We can use the <em>introspection</em> trick we learned in the <a href="http://python4kids.wordpress.com/2011/03/07/time-for-some-introspection/">second last tute</a> to find out a little about our <em>dictionary:</em></p>
<pre>&gt;&gt;&gt; print aDictionary.__doc__
dict() -&gt; new empty dictionary.
dict(mapping) -&gt; new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -&gt; new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -&gt; new dictionary initialized with the name=value pairs
in the keyword argument list.  For example:  dict(one=1, two=2)</pre>
<p><strong>Homework: </strong>try dir(aDictionary)</p>
<p>So, a<em> &#8220;dictionary&#8221; </em>has <em>&#8220;(key, value) pairs&#8221;</em> apparently.  What are these things?  You can think of <em>dictionaries</em> as a generalisation of <em>lists</em>.  In our earlier examples we got the contents of the <em>lists</em> by a number.  The number 0 was used to store the question in the trivia list (if you&#8217;ve forgotten it was in <a href="http://python4kids.wordpress.com/2010/09/06/trivial-lists/">this tute</a>).  In that case the number 0 was the<em> &#8220;key&#8221;, </em>and the text of the question was the<em> &#8220;value&#8221;. </em>A <em>list</em> only allows you to use numbers as <em>keys. </em> However, <em>dictionaries</em> don&#8217;t limit you in that way.  This means that you can give meaningful names to your <em>keys. </em>Let&#8217;s add something to our <em>dictionary:</em></p>
<pre>&gt;&gt;&gt; aDictionary["I would like to buy some matches"] = "My hovercraft is full of eels"
&gt;&gt;&gt; aDictionary
{'I would like to buy some matches': 'My hovercraft is full of eels'}</pre>
<p>Here the<em> &#8220;key&#8221; </em>is the string <em>&#8216;I would like to buy some matches&#8217;</em>.  The <em>value</em> is also a <em>string</em> &#8211; <em>&#8216;My hovercraft is full of eels&#8217;.</em> The print out indicates that the <em>object aDictionary</em> is a <em>dictionary</em> by enclosing the output in curly braces -&gt; {}.  Note also that we use the <em>key</em> to reference a <em>value</em> in the <em>dictionary</em> by using square brackets [] in much the same way as we used square brackets to identify members of the <em>list</em> in earlier tutes.</p>
<p>The <em>key &#8216;I would like to buy some matches&#8217; </em>is a somewhat unusual <em>key. </em>How about we add another (key, value) pair:</p>
<pre>&gt;&gt;&gt; aDictionary['it'] = 'The word the Knights of Ni! cannot stand'
&gt;&gt;&gt; aDictionary['Monty Python'] = "A famous comedy troupe from Britain, most active in the 70s and early 80s and on whom the name of the programming language Python is based."
&gt;&gt;&gt; aDictionary
{'I would like to buy some matches': 'My hovercraft is full of eels', 'Monty Python': 'A famous comedy troupe from Britain, most active in the 70s and early 80s and on whom the name of the programming language Python is based.', 'it': 'The word the Knights of Ni! cannot stand'}</pre>
<p>Here, <em>aDictionary</em> is acting how you would normally expect a dictionary (no italics, here I mean the sort of dictionary you&#8217;d find on a bookshelf) to operate &#8211; give it a word (<em>&#8216;it&#8217;</em>), and it gives you a meaning for the word.  You should also note here that there is no necessary ordering of a <em>dictionary</em>*1 &#8211; in this case <em>&#8216;it&#8217; </em>comes after <em>&#8216;Monty Python&#8217;</em> in the print out even though alphabetically <em>&#8216;it&#8217;</em> should come first.</p>
<p><em>Dictionaries</em> allow us to set up a direct relationship between the <em>key</em> and the <em>value. </em>In theory, <em>dictionaries</em> give you a speed advantage for looking up <em>values, </em>especially for a large number of <em>keys</em> (this is a result of how <em>dictionaries</em> are implemented).  The reason I use <em>dictionaries</em> is that they usually give me a better way to remember what I am talking about.  So for example, we used <em>sampleQuestion[1]</em> to refer to the correct answer in our <em>list. </em>However, why should &#8217;1&#8242; identify the correct answer?  If it was a <em>dictionary, </em>rather than a <em>list, </em>we could, instead, have written <em>sampleQuestion['correctAnswer']</em>.  This takes more typing, but in the long run is better because it is clearer what is going on with the code.</p>
<p>That said, <em>lists</em> can be massaged to address this readability issue.  One defines constants with a meaningful name, and then refers to elements by the constants:</p>
<pre>CORRECT_ANSWER = 1
sampleQuestion[CORRECT_ANSWER]  # (Same as sampleQuestion[1])</pre>
<p>By convention, if a variable is to be used as a constant (ie with a value which does not change) it is given a name consisting of all UPPERCASE LETTERS, as we have done here.  If all the letters are uppercase, there&#8217;s no ability for a change in case to indicate a separate word in the name, so we use underscores _ to add meaning.</p>
<p>However, <em>dictionaries</em> still provide some other advantages.  If you ever needed to change your data structure, you would be affected by the ordering of the <em>list. </em>In the data structure we&#8217;ve adopted for our trivia game, you could not, for example, include an alternative correct answer because there is literally nowhere to put it in the<em> list</em>*2 &#8211; the first entry is the question, the second entry is the right answer and the third <strong>and subsequent</strong> entries are wrong answers.  You can&#8217;t put it at the end, because that&#8217;s where wrong answers go and there&#8217;s nowhere else left up front.  However, if <em>sampleQuestion</em> was a <em>dictionary, </em>you just add another (key,value) pair (the <em>key</em> might be <em>&#8220;alternativeCorrectAnswer&#8221;</em>). <strong> Importantly this would not break any existing code which processed a dictionary with existing data.</strong>&lt;- in bold because it&#8217;s important!  Existing code would look for one of the existing <em>keys,</em> but would not be troubled by the existence of a new <em>key. </em></p>
<p>That said, the main reason I use <em>dictionaries</em> is not explicitly for this flexibility or for the potential speed advantage.  Rather, I find the concept easy to understand in the first place, and I also find it more easy to understand code which I have written previously if I&#8217;ve used a <em>dictionary.</em></p>
<p>You can get a <em>list</em> of <em>keys</em> in a <em>dictionary</em> (and a <em>list</em> of <em>values</em>):</p>
<pre>&gt;&gt;&gt; aDictionary.keys()
['I would like to buy some matches', 'Monty Python', 'it']
&gt;&gt;&gt; aDictionary.values()
['My hovercraft is full of eels', 'A famous comedy troupe from Britain, most active in the 70s and early 80s and on whom the name of the programming language Python is based.', 'The word the Knights of Ni! cannot stand']
&gt;&gt;&gt;</pre>
<p>More freaky however, is that you can iterate over all of the <em>keys</em> if you want to:</p>
<pre>&gt;&gt;&gt; for k in aDictionary.keys():
...     print "The key is -&gt;",k,"\nand its associated value is -&gt;",aDictionary[k]
...
The key is -&gt; I would like to buy some matches
and its associated value is -&gt; My hovercraft is full of eels
The key is -&gt; Monty Python
and its associated value is -&gt; A famous comedy troupe from Britain, most active in the 70s and early 80s and on whom the name of the programming language Python is based.
The key is -&gt; it
and its associated value is -&gt; The word the Knights of Ni! cannot stand</pre>
<p>Is that cool?  In this code each <em>key</em> in <em>aDictionary</em> is assigned in turn to the variable <em>k</em>, so the <em>value</em> corresponding to that key can be accessed by <em>aDictionary[k]. </em></p>
<p>I think it&#8217;s way cool.</p>
<p><strong>Homework: </strong>make a <em>dictionary</em> which has the name of your friends as <em>key</em>s, and the name of the friend&#8217;s favourite game as the <em>value</em> of the <em>key</em>.  Hint: the .<em>__doc__</em> printout above shows a fast way to create a <em>dictionary</em> populated with <em>key</em>s eg: <em>faveGames = dict(Arthur=&#8221;chess&#8221;,Hildegard=&#8221;Cortex Command&#8221;)</em></p>
<p><strong>PS: </strong></p>
<p>Here&#8217;s <a href="http://www.omniglot.com/language/phrases/hovercraft.htm">a site which translates &#8220;my hovercraft is full of eels&#8221; into various languages</a><em><br />
</em></p>
<p><strong>Notes:</strong><br />
*1 Python has another object which will give you an ordered dictionary, but we don&#8217;t need it at the moment.</p>
<p>*2 You could, if you were desperate, but it would take a bit of effort, and/or not work with (ie &#8216;break&#8217;) your existing data.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/209/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=209&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/04/06/dictionaries-hovercraft-eels/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Increasingly Trivial Questions</title>
		<link>http://python4kids.wordpress.com/2011/03/22/increasingly-trivial-questions/</link>
		<comments>http://python4kids.wordpress.com/2011/03/22/increasingly-trivial-questions/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 12:59:53 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=203</guid>
		<description><![CDATA[First Hermit     Hello, are you a hermit by any chance? Second Hermit     Yes that&#8217;s right. Are you a hermit? First Hermit     Yes, I certainly am. Second Hermit     Well I never. What are you getting away from? First Hermit     Oh you know, the usual &#8211; people, chat, gossip, you know. Second [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=203&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode08.htm#5"><em>First Hermit     Hello, are you a hermit by any chance?</em><br />
<em>Second Hermit     Yes that&#8217;s right. Are you a hermit?</em><br />
<em>First Hermit     Yes, I certainly am.</em><br />
<em>Second Hermit     Well I never. What are you getting away from?</em><br />
<em>First Hermit     Oh you know, the usual &#8211; people, chat, gossip, you know.</em><br />
<em>Second Hermit     Oh I certainly do &#8211; it was the same with me. I mean there comes a time when you realize there&#8217;s no good frittering your life away in idleness and trivial chit-chat.</em></a></p>
<p>If you remember back a few tutorials ago, we learnt how to <em>pickle</em> objects so that we could get them back later.  To <em>pickle</em> the object <em>triviaQuestions</em> (which was a <em>list</em> object) we first imported the <em>pickle</em> module, then opened a file and <em>dump</em>ed the object into the file, then <em>close()</em>d the file:</p>
<pre>-&gt;code snippet removed to note [1] because I don't want you typing it in&lt;-
</pre>
<p>Note here that when we opened the file with &#8216;w&#8217; this meant we were &#8216;w&#8217;riting to it.  If the file existed, then Python wiped it ready for us to write something new to it. You need to be careful when <strong>reading</strong> from a file that you have &#8216;r&#8217; (for &#8216;r&#8217;ead) in the <em>open()</em> command, otherwise, instead of reading the data, you&#8217;ll wipe it instead!!!!<br />
Let&#8217;s load the triviaQuestions list:</p>
<pre>&gt;&gt;&gt; import cPickle
&gt;&gt;&gt; filename = "p4kTriviaQuestions.txt"
&gt;&gt;&gt; fileObject = open(filename,'r')  # note the 'r' for 'read'
&gt;&gt;&gt; triviaQuestions = cPickle.load(fileObject)
&gt;&gt;&gt; len(triviaQuestions)
2
&gt;&gt;&gt; triviaQuestions[0]
['Who expects the Spanish Inquisition?', 'Nobody', 'Eric the Hallibut', 'An unladen swallow', 'Brian', 'Me!']
&gt;&gt;&gt; triviaQuestions[1]
['What is the air-speed velocity of an unladen swallow?', 'What do you mean?  African or European swallow?', '10 m/s', '14.4 m/s', '23.6 m/s']</pre>
<p>Wow! We have preserved the list between tutorials. So, rather than continually typing out all the questions every time, we only have to add new questions.</p>
<p>In this code we&#8217;ve imported <em>cPickle. </em>We mentioned <em>cPickle</em> earlier.  It does (for our purposes) the same thing as <em>pickle</em>, only it does it faster.  <em>cPickle</em> and <em>pickle</em> behave  little differently in some special circumstances, but that&#8217;s not relevant for us.  We also used &#8216;r&#8217; rather than &#8216;w&#8217; when we opened the file.  Also, <em>cPickle</em> doesn&#8217;t care about the name the object had when it was <em>dump()</em>ed.  We could have loaded the <em>pickle</em> into an object with a different name:</p>
<pre>&gt;&gt;&gt; fileObject.close()
&gt;&gt;&gt; fileObject = open(filename,'r')
&gt;&gt;&gt; aList = cPickle.load(fileObject)
&gt;&gt;&gt; fileObject.close()
&gt;&gt;&gt; aList == triviaQuestions
True</pre>
<p>We had to first <em>close()</em> the <em>fileObject</em> so that <em>cPickle</em> read from the start of the file.  If there are multiple objects pickled to a file it loads them out in the order they were dumped in.  So once it <em>load()</em>s an object <em>cPickle</em> has moves to the end of the object in the file in order to read the next object.  If there is only one object, then cPickle will be at the end of the file and won&#8217;t be able to read any more.</p>
<p>As we can see, we&#8217;ve <em>load()</em>ed the same object under a different name (<em>aList</em>).  You should also note here that when an object is <em>load()</em>ed, it doesn&#8217;t change the file (unlike when an object is <em>dump()</em>ed).  We could load multiple copies of the object for ever if we wanted to.<br />
Let&#8217;s add another question and then dump the list to the file:</p>
<pre>sampleQuestion = []
# this clears the earlier entries
# if we append without doing this
# we'll have multiple questions in the wrong list
# first the question
sampleQuestion.append("Is this the right room for an argument?")
# then the correct answer
sampleQuestion.append("I've told you once.")
# now one or more incorrect answers
sampleQuestion.append("No")
sampleQuestion.append("Down the hall, first on the left")
sampleQuestion.append("Yes")</pre>
<p>now we <em>append()</em> this question to the end of the list:</p>
<pre>triviaQuestions.append(sampleQuestion)</pre>
<p>Finally, we dump the object back into the file.  Be careful &#8211; when we open the file to write (&#8216;w&#8217;) we lose what&#8217;s saved in it.  That&#8217;s no problem if we fill it back up with data, so be sure to dump the question list!</p>
<pre>&gt;&gt;&gt; fileObject = open(filename,'w')  # data that was in the file is now gone!
&gt;&gt;&gt; cPickle.dump(triviaQuestions,fileObject)   # ok, put new data in
&gt;&gt;&gt; fileObject.close()</pre>
<p>If you were worried about losing your data you would first <em>dump() </em>the object to a file with a temporary name, then when that was successful, rename the existing file as &#8216;p4kTriviaQuestions.bak&#8217;  and the newly created file to &#8216;p4kTriviaQuestions.txt&#8217;.  Then if anything went wrong with saving the data you would still have the data backed up in the &#8220;.bak&#8221; file.</p>
<p><strong>Homework:</strong></p>
<ul>
<li>add some more questions to your triviaQuestions list by <em>load()ing </em> the list from your file, adding questions, then <em>dump()ing </em> the list back to the file. Make sure you use &#8216;r&#8217; when you open a file you are going to <em>load() </em>from and &#8216;w&#8217; when you open a file to <em>dump() </em>to.</li>
</ul>
<p>Notes:</p>
<p>[1] This is repeated from the <a href="http://en.wiktionary.org/wiki/penultimate">penultimate</a> <a href="http://python4kids.wordpress.com/2011/02/24/a-big-jar-of-pickles/">tute</a> (or <a href="http://en.wiktionary.org/wiki/antepenultimate">antepenultimate</a> if you are counting this tute):</p>
<pre>&gt;&gt;&gt; import pickle
&gt;&gt;&gt; # This is just a flashback don't retype this code because it will wipe your data!!!!
&gt;&gt;&gt; filename = "p4kTriviaQuestions.txt"
&gt;&gt;&gt; fileObject = open(filename,'w')
&gt;&gt;&gt; pickle.dump(triviaQuestions,fileObject)
&gt;&gt;&gt; fileObject.close()</pre>
<p>&nbsp;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/203/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=203&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/03/22/increasingly-trivial-questions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>Time for Some Introspection</title>
		<link>http://python4kids.wordpress.com/2011/03/07/time-for-some-introspection/</link>
		<comments>http://python4kids.wordpress.com/2011/03/07/time-for-some-introspection/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 04:27:02 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=198</guid>
		<description><![CDATA[&#8220;&#8230;The illusion is complete; it is reality, the reality is illusion and the ambiguity is the only truth. But is the truth, as Hitchcock observes, in the box? No there isn&#8217;t room, the ambiguity has put on weight. The point is taken, the elk is dead, the beast stops at Swindon, Chabrol stops at nothing, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=198&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ibras.dk/montypython/episode24.htm#6"><span id="John">&#8220;&#8230;The illusion is complete; it is reality, the reality is  illusion and the ambiguity is the only truth. But is the truth, as  Hitchcock observes, in the box? No there isn&#8217;t room, the ambiguity has  put on weight. The point is taken, the elk is dead, the beast stops at  Swindon, Chabrol stops at nothing, I&#8217;m having treatment and La Fontaine  can get knotted.&#8221;</span></a></p>
<p>Did you notice some errors in the previous tutorial? One was fatal.  The fact that no one commented on them indicates to me that no one is actually typing in the code &#8211; naughty naughty!  Type it in.  It&#8217;s important.</p>
<p>The errors have been corrected now, but they were:</p>
<pre>pickle.dump(fileObject, triviaQuestions)</pre>
<p>(the order of the arguments is wrong, the object to dump goes first, and the file object to dump it into goes next); and<br />
there was a stray full stop at the end of one line.</p>
<p>If you typed in the previous tutorial you should have received the following error:</p>
<pre>&gt;&gt;&gt; pickle.dump(fileObject,triviaQuestions)
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
File "/usr/lib64/python2.6/pickle.py", line 1362, in dump
Pickler(file, protocol).dump(obj)
File "/usr/lib64/python2.6/pickle.py", line 203, in __init__
self.write = file.write
AttributeError: 'list' object has no attribute 'write'</pre>
<p>Or something like it &#8211; the exact error may be different depending on what version of python you are running.</p>
<p>If you receive an error like this you can always use the interpreter&#8217;s built in help function to assist:</p>
<pre>&gt;&gt;&gt; help(pickle.dump)
Help on function dump in module pickle:

dump(obj, file, protocol=None)</pre>
<p>This is not entirely enlightening, but it does tell you that the order of the  arguments &#8211; the object first, followed by the file second, followed by a third, optional, argument (protocol).  We know it is optional because it is assigned a default value.</p>
<p>The object itself is also able to tell you about itself.  This is called &#8220;introspection&#8221;.  In English introspection means looking inward.  People who are introspective spend time thinking about themselves.   In Python, introspection is the ability of the program to examine, or give information about, itself.   For example, try this:</p>
<pre>&gt;&gt;&gt; print pickle.__doc__
Create portable serialized representations of Python objects.</pre>
<pre>See module cPickle for a (much) faster implementation.
See module copy_reg for a mechanism for registering custom picklers.
See module pickletools source for extensive comments.</pre>
<pre>Classes:</pre>
<pre>Pickler
Unpickler</pre>
<pre>Functions:</pre>
<pre>dump(object, file)
dumps(object) -&gt; string
load(file) -&gt; object
loads(string) -&gt; object</pre>
<pre>Misc variables:</pre>
<pre>__version__
format_version
compatible_formats</pre>
<p>This shows the &#8220;docstring&#8221; for the pickle module.  Docstring is a string which holds documentation about the object.   We have learnt from the docstring that pickle has methods for dumping object to strings as well as files.   Any object can have a docstring, for example, our triviaQuestions list had one [if you redo the previous tute to reconstruct it, since we haven't instantiated it this time]:</p>
<pre>&gt;&gt;&gt; triviaQuestions.__doc__
"list() -&gt; new empty list\nlist(iterable) -&gt; new list initialized from iterable's items"</pre>
<p>In this case, the docstring is the same for all lists (try [].__doc__).  However, some objects, particularly classes (which we haven&#8217;t met yet) and functions, are able to have their own docstrings which are particular to that object.   A docstring can be created for an object by adding a comment in triple single quotes (&#8221;&#8217;) at the start of the object&#8217;s definition (other comment forms like single quotes work, but triple single quotes are the convention so that you can include apostrophes etc in the docstring):</p>
<pre> &gt;&gt;&gt; def square(x):
...     '''Given a number x return the square of x (ie x times x)'''
...     return x*x
...
&gt;&gt;&gt; square(2)
4
&gt;&gt;&gt; square.__doc__
'Given a number x return the square of x (ie x times x)'</pre>
<p>When you write code you should also write docstrings which explain what the code does.  While you may think you&#8217;ll remember what it does in the future, the reality is that you won&#8217;t!</p>
<p>How did I know that pickle had it&#8217;s own docstring?  Well, I read it somewhere, like you read it here.  However, if you ever find yourself needing to work out what forms part of an object Python has a function to do it &#8211; it&#8217;s called dir().  You can use it on any object.  Let&#8217;s have a look at it on the square() function we just made up:</p>
<p style="padding-left:30px;">&gt;&gt;&gt; dir(square)<br />
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']</p>
<p>I bet you didn&#8217;t realise that the function we just defined now had so many attributes/methods!!  You can see that __doc__ is one of them.  Where an attribute starts with two underscores &#8216;__&#8217; it&#8217;s got a special meaning in Python.   You can pronounce the two underscores in a number of different ways including: &#8220;underscore underscore&#8221;, &#8220;under under&#8221;, &#8220;double underscore&#8221;, &#8220;double under&#8221; and, my favourite, &#8220;dunder&#8221;.</p>
<p>To tell whether these are <em>methods</em> (think functions) rather than <em>attributes</em> (think values) you can use the <em>callable()</em> function:</p>
<pre>&gt;&gt;&gt; callable(square.__repr__)
True
&gt;&gt;&gt; callable(square.__doc__)
False</pre>
<p>If it is callable, then you can add parentheses to it and treat it like a function (sometimes you will need to know what arguments the callable takes):</p>
<pre>&gt;&gt;&gt; square.__repr__()
'&lt;function square at 0x7f0b977fab90&gt;'</pre>
<p>The<em> __repr__()</em> method of an object gives a printable version of the object.</p>
<p>When something goes wrong with your program you can use Python&#8217;s introspection capabilities to get more information about what might have gone wrong and why.  Also, don&#8217;t forget to check the Python docs!</p>
<p><strong>Homework:</strong></p>
<ul>
<li>go over previous tutes and identify 3 objects</li>
<li>for each of these objects:
<ul>
<li>re-do the relevant tute to instantiate (ie create) each of these objects;</li>
<li>look at the docstring for the object (print objectName.__doc__); and</li>
<li>look at the directory listing for the object (print dir(objectName)).</li>
</ul>
</li>
<li>Extra marks:
<ul>
<li>find some callable methods in one listing and call them.</li>
</ul>
</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/198/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/198/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=198&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/03/07/time-for-some-introspection/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>A Big Jar of Pickles</title>
		<link>http://python4kids.wordpress.com/2011/02/24/a-big-jar-of-pickles/</link>
		<comments>http://python4kids.wordpress.com/2011/02/24/a-big-jar-of-pickles/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 07:01:43 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=191</guid>
		<description><![CDATA[Pither (voice over) As I lay down to the sound of the Russian gentlemen practising their shooting, I realised I was in a bit of a pickle. My heart sank as I realised I should never see the Okehampton by-pass again&#8230; In the last tutorial we learned how to pickle our objects.  Pickling is a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=191&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.ibras.dk/montypython/episode34.htm#7">Pither  <span id="Michael">(voice over) As I lay down to the sound of the  Russian gentlemen practising their shooting, I realised I was in a bit  of a pickle. My heart sank as I realised I should never see the  Okehampton by-pass again&#8230;</span></a></em></p>
<p>In the last tutorial we learned how to pickle our objects.  Pickling is a way of storing the object (on the computer&#8217;s file system) so that it can be used later.   This means that if we want to re use an object we can simply save it and load it when we need it, rather than re-creating it each time we want to use it.  This is very useful when our object is a list of questions for our trivia game.  We really only want to type the questions in once and then reload them later.</p>
<p>Now we need to settle on a way to structure our data.  We saw in our earlier tutorial that each question was a list, and that the list itself had a certain structure.  We also need to think about how a number of questions will be stored.  We will use a list to do that as well!  In this case we will have a list of questions.  Each of the elements in the list will itself be a list.  Let&#8217;s build one.  First we make an empty list to store all the questions:</p>
<pre>triviaQuestions=[]</pre>
<p>It is empty:</p>
<pre>len(triviaQuestions)</pre>
<p>Next, let&#8217;s make a sample question to add to that list.  Feel free to use your own question/ answers if you want to use your own topic:</p>
<pre>sampleQuestion = []</pre>
<p>Now, we populate the sample question:</p>
<pre>sampleQuestion.append("Who expects the Spanish Inquisition?")
# first entry must be the question
sampleQuestion.append("Nobody")
# second entry must be the correct answer
sampleQuestion.append("Eric the Hallibut")
sampleQuestion.append("An unladen swallow")
sampleQuestion.append("Brian")
sampleQuestion.append("Me!")
# any number of incorrect answers can follow
# but they must all be incorrect</pre>
<p>There are 6 elements in the sampleQuestion list:</p>
<pre>len(sampleQuestion)</pre>
<p>Now, we add the sample question (as the first entry) to the list of trivia questions:</p>
<pre>triviaQuestions.append(sampleQuestion)</pre>
<p>It now has one question in it:</p>
<pre>len(triviaQuestions)</pre>
<p>To add more questions we &#8220;rinse and repeat&#8221;:</p>
<pre>sampleQuestion = []
# this clears the earlier entries
# if we append without doing this
# we'll have multiple questions in the wrong list
sampleQuestion.append("What is the air-speed velocity of an unladen swallow?")
sampleQuestion.append("What do you mean?  African or European swallow?")
sampleQuestion.append("10 m/s")
sampleQuestion.append("14.4 m/s")
sampleQuestion.append("23.6 m/s")

triviaQuestions.append(sampleQuestion)</pre>
<p>Now, the sampleQuestion has five entries and there are two questions in total:</p>
<pre>len(sampleQuestion)
len(triviaQuestions)</pre>
<p>Now we need to save the question list so we can use it again later.  We will save it to a file called &#8220;p4kTriviaQuestions.txt&#8221;.  Ideally we would test to see whether this file already exists before first creating it (so that we don&#8217;t inadvertently wipe some valuable file).  Today however, we&#8217;re just crossing our fingers and hoping that you don&#8217;t already have a file of this name in your directory:</p>
<pre>import pickle
fileName = "p4kTriviaQuestions.txt"
fileObject = open(fileName,'w')
pickle.dump(triviaQuestions,fileObject)
# oops! earlier draft had these in the wrong order!
fileObject.close()</pre>
<p>So far we have spent a lot of time on how to store the data used by the game.  However, in order to hang the various parts of the trivia game together we need to learn about storing a different part of the game &#8211; the program itself.  We will be looking at that in the coming tutorials.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/191/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=191&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/02/24/a-big-jar-of-pickles/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
		<item>
		<title>An Awful Pickle</title>
		<link>http://python4kids.wordpress.com/2011/02/04/an-awful-pickle/</link>
		<comments>http://python4kids.wordpress.com/2011/02/04/an-awful-pickle/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 12:46:36 +0000</pubDate>
		<dc:creator>brendanscott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://python4kids.wordpress.com/?p=178</guid>
		<description><![CDATA[Specialist     Come in. The door opens and Raymond Luxury Yacht enters. He cannot walk straight to the desk as his passage is barred by the strip of wood carrying the degrees, but he discovers the special hinged part of it that opens like a door. Mr Luxury Yacht has his enormous polystyrene nose. It [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=178&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.ibras.dk/montypython/episode22.htm#5">Specialist     Come in.<br />
The door opens and Raymond Luxury Yacht enters. He cannot walk straight to the desk as his passage is barred by the strip of wood carrying the degrees, but he discovers the special hinged part of it that opens like a door. Mr Luxury Yacht has his enormous polystyrene nose. It is a foot long.<br />
Specialist     Ah! Mr Luxury Yacht. Do sit down, please.<br />
Mr Luxury Yacht     Ah, no, no. My name is spelled &#8216;Luxury Yacht&#8217; but it&#8217;s pronounced &#8216;Throatwobbler Mangrove&#8217;.<br />
Specialist     Well, do sit down then Mr Throatwobbler Mangrove.<br />
Mr Luxury Yacht     Thank you.</a></em><br />
So, we know how to save trivia questions to a file, and how to read them back from a file in the future.  Moreover, we have decided on a particular way of structuring the data which makes a question.  That is, the question is followed by the correct answer and then a number of incorrect answers.   Now we have to translate between a list (which has a concept of elements), and a file (which doesn&#8217;t).  Files are &#8220;flat&#8221; &#8211; which is to say that they have no sense of structure, they are simply a stream of data.  A file may record all of the characters which are the questions and answers, but it wouldn&#8217;t record the fact that they are a list or, indeed, that they are any kind of Python object.  I was originally just going to run with this to let you find out about files, but I have instead decided to introduce a further concept &#8211; the Python <em>pickle</em>!</p>
<p><em>pickle</em> is a module which allows you to store Python objects including their structure.  That means after you have <em>pickle</em>d an object to a file, you can later load that object back up from the file and all the structure associated with that object will be preserved.  While, at the moment, we are only dealing with a list, any object can be <em>pickle</em>d &#8211; even if it has methods and attributes (ie functions and data which are packaged with the object) &#8211; they are saved with the object in the file.  What <em>pickle</em> does is &#8220;serialises&#8221; the object first before &#8220;persisting&#8221; it.<br />
To use <em>pickle</em> you must first import it:</p>
<pre>import pickle</pre>
<p><em>pickle</em> has two main methods &#8211; <em>dump</em>, which dumps an object to a file object and <em>load</em>, which loads an object from a file object.  Note here that the file object referred to here is what is returned by the <em>open()</em> function.  It is <span style="text-decoration:underline;">not</span> the name of the file.  So to use <em>pickle</em> you must first <em>open()</em> the file (either as &#8216;w&#8217; if you are dumping an object or as &#8216;r&#8217; if you are loading one) and store the object that the <em>open()</em> function returns.  I will demonstrate by making a demo list object and pickling it to a file called &#8216;testfile&#8217;:</p>
<pre>a = ['A dummy question','The correct answer','A wrong answer']
a
['A dummy question', 'The correct answer', 'A wrong answer']
fileName = "testfile"
fileObject = open(fileName,'w') # open the file for writing
import pickle
pickle.dump(a,fileObject)   # this writes the object a to the file named 'testfile'
fileObject.close()
fileObject = open(fileName,'r')  #open the file for reading
b = pickle.load(fileObject)  #load the object from the file into b
b
['A dummy question', 'The correct answer', 'A wrong answer']
a==b
True</pre>
<p>You can see that what is now in <em>b</em> is the same as what is in <em>a</em> (because <em>a==b </em>is <em>True</em>, Python thinks they are the same).  Moreover, this dump/load procedure allows you to preserve the object even when you quit of of python and come back to it later (which is the whole point of this exercise):</p>
<pre>fileObject.close()
exit()  # leave python and restart
/home/user&gt; python
Python 2.5 (release25-maint, Dec  9 2006, 14:35:53)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; import pickle
&gt;&gt;&gt; fileName = 'testfile'
&gt;&gt;&gt; fileObject = open(fileName,'r')
&gt;&gt;&gt; c = pickle.load(fileObject)  #load the old object
&gt;&gt;&gt; c
['A dummy question', 'The correct answer', 'A wrong answer']</pre>
<p>However, now we try to compare <em>c </em>to the original we see that Python has forgotten <em>a</em> when we exited:</p>
<pre>c==a
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'a' is not defined</pre>
<p>Which is to say that the only place that python got the object <em>c</em> from was the file when it <em>pickle.load()</em>ed.</p>
<p><strong>Homework:</strong><br />
Make some other objects, dump them to a file and load them again.  Make sure that you name the file first then <em>open()</em> it before you <em>pickle</em> and <em>.close()</em> it afterwards.  Use the attribute &#8216;w&#8217; when you open a file to dump an object and &#8216;r&#8217; when you are going to load an object.</p>
<p><strong>Pickle vs cPickle:</strong></p>
<p>Python actually has two pickle modules &#8211; <em>pickle</em>, which we used above and <em>cPickle</em>. There are some technical differences between them but for most purposes they can be treated as being exactly the same.  The main difference is that <em>cPickle</em> has been written in the C programming language and, as a result, runs much faster.  While I am using <em>pickle</em> here, in future tutorials I will (try to remember to) use cPickle instead.  When you write your own programs you should use the <em>cPickle</em> module by default as it will run faster (ie. wherever you see <em>pickle</em>, use <em>cPickle</em> instead).  Otherwise the usage is exactly the same.</p>
<p>Spelling Note: It is pick<span style="text-decoration:underline;">le</span> not pick<span style="text-decoration:underline;">el</span>.</p>
<p><em><br />
</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/python4kids.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/python4kids.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/python4kids.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/python4kids.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/python4kids.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/python4kids.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/python4kids.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/python4kids.wordpress.com/178/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=python4kids.wordpress.com&amp;blog=14472219&amp;post=178&amp;subd=python4kids&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://python4kids.wordpress.com/2011/02/04/an-awful-pickle/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6cf1edc97aa47b5d1cdddeecadf2e8ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brendanscott</media:title>
		</media:content>
	</item>
	</channel>
</rss>
