Python in Education
Python in Education
Python in
Education
Teach, Learn, Program
Nicholas H. Tollervey
ISBN: 978-1-491-92462-4
Python in Education
Nicholas H.Tollervey
Python in Education
by Nicholas H. Tollervey
Copyright 2015 OReilly Media, Inc. All rights reserved.
Printed in the United States of America.
Published by OReilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA
95472.
OReilly books may be purchased for educational, business, or sales promotional use.
Online editions are also available for most titles (http://safaribooksonline.com). For
more information, contact our corporate/institutional sales department:
800-998-9938 or [email protected].
First Edition
978-1-491-92462-4
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
1. The Story of Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2. A Pythonic Case Study:
Raspberry Pi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3. Why Python in Education?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Code Readability
Obvious Simplicity
Open Extensibility
Cross-Platform Runability
Humanity
13
15
20
21
24
26
27
5. Looking Ahead. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Preface
Programming is cool.
Why?
Because programmers are obviously black-clad kung-fu ninjas with
hacker aliases who always take the red pill, type really fast to
crack databases, and save the world from renegade artificial intelli
gences.1 Or perhaps programmers are geeky wunderkind who make
billions of dollars by founding social networks that have more users
than most countries have citizens.2 Then again, programmers are
those socially awkward yet rather useful savants who are always so
keen to fix your computer (but never let them explain what theyre
doing or theyll bore you with overly enthusiastic technobabble).3
Also, why is programming such a boy thing?
Stereotypes stop people from doing stuff.
This applies as much to programming as any other aspect of life. If
your view of a programmer is as ridiculous as the stereotypes listed
above, then programming is likely to appear as an intimidating form
of technical magic or a dull obsession for misfit boys who avoid the
great outdoors.
But there is hope: the damaging prejudices and misconceptions lis
ted above can be overturned through education. Organizations such
as the RaspberryPi Foundation and One Laptop Per Child (OLPC)
vii
Python Is Everywhere
A quick glance online suggests that Python is the language du jour
for teaching programming. Yet Python is, and has been for a while,
one of the worlds most popular programming languages in industry
as well. Every day, without realizing it, you probably use software
that is written using Python. Python is used by companies to write
all sorts of applications. Google, NASA, Bank of America, Disney,
CERN, YouTube, Mozilla, The Guardianthe list goes on of compa
nies and organizations of all sizes in all sectors of the economy that
use Python.
Why is Python so popular?
I aim to answer this question from an educational perspective. One
might distill the answer into the following points:
Resources
There are lots of resources for learners of all ages and levels.
These range from traditional textbooks to websites that offer
online self-paced courses in Python programming. With the
advent of the Raspberry Pi and OLPC projects, everyone can get
hold of affordable hardware that runs Python.
The Languages Design
Python is easy to learn, intuitive, pleasing to the eye and comes
with a plethora of libraries that allow programmers to build all
sorts of applications addressing different domains and activities.
viii
Preface
Its easy to read: if you squint a little, most Python code is com
prehensible even to people who wouldnt call themselves pro
grammers (for example, Python is very popular among
scientists).
Community
Python has a large, diverse and proactive community associated
with it. The Python Software Foundation (PSF) is a communityled charitable organization whose mission is to promote, pro
tect and advance the Python programming language.
Momentum
Being popular is itself a strength and a virtuous circle that rein
forces Pythons popularity. New projects and initiatives are
announced all the time. For example, the author is aware of sev
eral yet-to-be publicly announced Python-in-education
projects. The online version of this document will be updated to
reflect these announcements, so be sure to check http://
www.oreilly.com/programming/free/python-in-education.csp.
Youre a Programmer
If you already know how to write code, then you might believe that
education is of little interest to you.
But wait!
If youre a good programmer, you also know that part of the vocation
of software development involves learning new technology and,
when in a position of responsibility, teaching junior colleagues how
your software works. Put simply, to be a programmer is to be both a
teacher and a student.
To describe programming so children understand you indicates that
you know your craft at a deep level. For instance, you appreciate
what to leave in or how much to leave out of an explanation. You
Preface
ix
Youre a Teacher
Well done! Before becoming a programmer, I was a senior secon
dary school teacher in the United Kingdom. It was the most difficult
yet also most rewarding job I have ever had to do. Teaching is the
one profession that creates all the other professions. It is a calling
(youre certainly not doing it for the money or perks) and, as a prac
titioner of this remarkable profession, if youre looking for help and
support in teaching programming, then youve made a great choice
by investigating Python.
This report describes where to learn about Python (so youre no
longer one page ahead of the class), get involved with and find sup
port from the wider Python community and become acquainted
with the story of Pythonan interesting subject in itself when
teaching computing.
Youre a Student
It often seems daunting to learn new skills and knowledge. But rest
assured, Python is both relatively easy to learn and a real program
ming language used widely in industry. Python comes with batter
ies included: there are plenty of libraries of code written in Python
that allow you to build all sorts of amazing and incredible applica
tions.
Pythons community is a welcoming and friendly place. Remember,
what you get out of the community is directly related to what you
put in. Dont just sit there, do something! Jump in and get involved.
Preface
This report explains where to learn Python (so youre several pages
ahead of your teacher in programming classes) and how to get in
touch with the wider community.
Youre a Parent
Someone you care about is obviously passionate about computers
and programming. Thats a good thingif they make it their career,
theyre joining a profession that has a high demand for quality engi
neers.
This report gives you enough information so you can best support
your loved one. Hopefully, it will allay any fears and uncertainties
you may have and answer some of your questions about learning to
program with Python.
Acknowledgments
Many thanks to Amelia Watkiss, Samuel Tollervey and William Toll
ervey for the moment of adventuring into Python captured on the
front cover of this document. Thanks also to Carrie Anne Philbin,
Naomi Ceder and Tim Golden for invaluable feedback on an early
draft. The picture of a fractal tree built in Minecraft was provided by
the extraordinarily creative Martin OHanlon. Finally, Meghan
Blanchette has, yet again, been a very patient editor.
Preface
xi
CHAPTER 1
1 From the foreword to Mark Lutzs book Programming Python (1st ed.), published by
OReilly. http://www.python.org/doc/essays/foreword/
Python could grow into the hugely popular and flexible language it
is today, capable of simply and effectively addressing many different
types of computational problems.
Van Rossum is now the Benevolent Dictator For Life (BDFL) for the
Python language and continues to make core contributions to the
language along with many thousands of developers spread all over
the world. From such curious beginnings, Python has grown to be a
major open source software project. Why? What is it about Python
that has made it so successful? What are the guiding principles that
attract such a large group of programmers, both amateur and pro
fessional, to work with and contribute to Python?
A handy answer is the Zen of Python. Its author, Tim Peters,
describes it as a document that succinctly channels the BDFLs
guiding principles for Pythons design into 20 aphorisms, only 19 of
which have been written down.
To read the Zen of Python, one simply starts the Python interpreter
and types the command import this:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious
way to do it.
Although that way may not be obvious at first unless
you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Exploring how learners used Python was going to inform the devel
opment of new programming languages and tools. These opening
paragraphs also beautifully encapsulate Pythons strengths in the
context of education.
Unfortunately the project was never finished due to a lack of fund
ing. I find it an interesting (and rather frustrating) what if?. How
might Python and computing education have developed if the
project had delivered on all three of the planned components?
In any case, this is yet more evidence of how Python has always had
education as a core focus. The proposal also appears prescient given
the recent changes in attitude to the computing curriculum and the
promotion of programming. Van Rossum was a decade and a half
too early. Could such a project be revived today?
Nevertheless, such educational endeavors did not go unnoticed.
Projects concerned with computing and education have successfully
made use of Python to great effect. For example, the One Laptop Per
Child (OLPC) project has the following aim:
The user interface and applications for the OLPC were written in
Python. Over 2.5 million children and teachers in 42 countries have
such laptops.
Perhaps the most famous and successful computing-in-education
project in history is the Raspberry Pi (with over 5 million devices
delivered so far). Unsurprisingly, Python is at the heart of the
project. The next chapter is a case study exploring why the Rasp
berry Pi Foundation chose to focus on Python and how this has led
to some unexpected yet wonderful outcomes.
CHAPTER 2
1 In mid-February 2015, the author visited the Raspberry Pi Foundation to discuss their
use of Python.
Figure 2-1. A Raspberry Pi (note the GPIO pins running across the top
of the board)
10
11
12
CHAPTER 3
Code Readability
When I write a to-do list on a piece of paper, it looks something like
this:
Shopping
Fix broken gutter
Mow the lawn
13
Intuitively we understand that the main tasks are broken down into
sub-tasks that are indented underneath the main task to which they
relate. This makes it easy to see, at a glance, how the tasks relate to
each other.
This is called scoping.
Indenting in this manner is also how Python organizes the various
tasks defined in Python programs. For example, the following code
simply says that there is a function called say_hello that asks the
user to input their name, and thenyou guessed itprints a
friendly greeting:
def say_hello():
name = input('What is your name? ')
print('Hello, ' + name)
14
code written using the Perl programming language will look for
duplicate words in a text document:
print "$.: doubled $_\n" while /\b(\w+)\b\s+\b\1\b/gi
Obvious Simplicity
The simple core concepts and knowledge required to write Python
code will get you quite far. That they are easy to learn, use and
remember is another characteristic in Pythons favor. Furthermore,
Python is an obvious programming languageit tries to do the
expected thing and will complain if you, the programmer, attempt to
do something clearly wrong. Its also obvious in a second senseit
names various concepts using commonly understood English
words.
Consider the following two examples.
In some languages, if you want to create a list of things, you have to
use variously named constructs such as arrays, arraylists, vectors
and collections. In Python, you use something called a list. Heres
my to-do list from earlier written in Python:
todo_list = ['Shopping', 'Fix broken gutter', 'Mow the lawn']
Obvious Simplicity
15
17
the final block of code that actually defines the behavior of the game.
It is my hunch, even if youre not a programmer, that youll be able
to get the gist of how it works.
"""
A very simple adventure game written in Python 3.
The "world" is a data structure that describes the game
world we want to explore. It's made up of key/value fields
that describe locations. Each location has a description
and one or more exits to other locations. Such records are
implemented as dictionaries.
The code at the very end creates a game "loop" that causes
multiple turns to take place in the game. Each turn displays
the user's location, available exits, asks the user where
to go next and then responds appropriately to the user's
input.
"""
world = {
'cave': {
'description': 'You are in
'exits': {
'up': 'courtyard',
},
},
'tower': {
'description': 'You are at
'exits': {
'down': 'gatehouse',
},
},
'courtyard': {
'description': 'You are in
'exits': {
'south': 'gatehouse',
'down': 'cave'
},
},
'gatehouse': {
'description': 'You are at
'exits': {
'south': 'forest',
'up': 'tower',
'north': 'courtyard',
},
},
'forest': {
'description': 'You are in
18
a mysterious cave.',
a forest glade.',
'exits': {
'north': 'gatehouse',
},
},
}
Obvious Simplicity
19
Open Extensibility
Despite the powerful simplicity of the core language, programmers
often need to reuse existing library modules of code to achieve a
common task. A library module is like a recipe book of instructions
for carrying out certain related tasks. It means programmers dont
have to start from scratch or reinvent the wheel every time they
encounter a common problem.
While most programming languages have mechanisms to write and
reuse libraries of code, Python is especially blessed in having a large
and extensive standard library (built into the core language), as well
as a thriving ecosystem of third-party modules.
For example, a common task is to retrieve data from a website. We
can use the requests third-party module to download web pages
using Python:
>>> import requests
>>> response = requests.get('http://python.org/')
>>> response.ok
True
>>> response.text[:42]
'<!doctype html>\n<!--[if lt IE 7]>
<html '
(This code tells Python that we want to use the requests library, gets
the HTML for Pythons home page, checks that the response was a
success [it was] and displays the first 42 characters of the resulting
HTML document.)
Some modules, such as requests, do one thing and do it exception
ally well. Other modules are organized into large libraries to create
application frameworks that solve many of the repetitive tasks
needed when writing common types of application.
20
Cross-Platform Runability
Python is a platform-agnostic language: it works on Microsoft Win
dows, Mac OS X, Linux and many other operating systems and devi
ces. Its even possible to have Python as a service through websites
such as Python Anywhere.
This is important in an educational context because Python works
on the computers used in schools. Students can also use it on the
computers they have at home, no matter the make or model they
may own. Furthermore, Python as a service provided via a website is
an excellent solution to the problem of the infamously troll-like
Cross-Platform Runability
21
22
Cross-Platform Runability
23
Humanity
While not a strict feature of the language, Pythons community, his
tory and philosophy often shines through code written in Python.
The odd Monty Python reference (the website that hosts third-party
Python modules is called the Cheese Shop after the sketch about a
cheese shop with no cheese), a playful sense of fun (for instance,
the PyPy project is so named because it is a high-performance ver
sion of Python written in Python) and other apparent eccentricities
bestow upon Python the appearance of an approachable and inter
esting language. Its obviously used by humans for humans rather
than being an abstract tool for esoterics.
Pythons community is a friendly and diverse bunch. It is to this
community of developers, teachers and students that I want to turn
in the next chapter.
Put simply, the Python community is the secret weapon of its
success.
24
CHAPTER 4
25
The PSF
Heres how the PSF describes itself:
The Python Software Foundation (PSF) is a volunteer led organiza
tion devoted to advancing open source technology related to the
Python programming language. It qualifies under the US Internal
Revenue Code as a tax-exempt 501(c)(3) scientific and educational
public charity, and conducts its business according to the rules for
such organizations.
The PSF was created to promote, protect, and advance the Python
programming language and to support and facilitate the growth of a
diverse and international community of Python programmers. This
is achieved by supporting the development of the Python program
ming language itself (whose intellectual property belongs to the
PSF), providing technical infrastructure for the Python community
(such as servers, mailing lists and the Python website), running and
supporting various international Python conferences (or Pycons,1
such as the one held in the UK mentioned in Chapter 2), and the
giving of grants to individuals and organizations for projects related
to the development of Python, Python-related technology, and edu
cational resources.
Anyone who is a user or supporter of Python can join and volunteer
as little or much as they see fit. The Python website and PSF should
be your first port of call for information relating to the Python com
munity. It includes the complete documentation for the language
(and tutorials, too).
The PSF also hosts several mailing lists that cater to various locales
and interests. For example, there is an education special interest
group mailing list that you can join (the web page for the Edu-SIG
also includes many useful links for resources and evidence of
Pythons efficacy as an educational programming language).
Another important aspect of the PSFs work is outreach and helping
to make the community a welcoming place for newcomersno
matter their background, age or level of experience. This is manifes
ted in several ways.
26
Conferences
Like every international community of free software developers,
many members collaborate over the Internet rather than in real life.
As a result, conferences are an important part of the community
because they literally bring people together. Friendships are
strengthened, collaborators are found and ideas are debated. Code is
furiously written during code sprints (intense days of group pro
gramming). There are also the usual conference events: talks, tutori
als, dinners and keynote speeches.
More recently in the world of Python conferences, things have taken
a decidedly educational turn. Since 2012, PyconUK has had teachers
attend and give presentations. In 2013, PyconUK had a specialist
education track for teachers and developers to come together and
learn from each other. Since 2013, the education track at PyconUK
has had a day set aside for kids to attend with their families. Next
year, PyconUK expects about 50 teachers and 150 kids to attend
over the course of two days during the main conference.
In North America, there has been a PyCon Education Summit for
developers and teachers since 2013 (and since as early as 2003, there
have been education-themed open spaces). Also in 2013, a kids
track was initiated where developers volunteer their time to teach
young coders and help them take their first steps into the world of
Python.
Conferences
27
28
CHAPTER 5
Looking Ahead
29