- University Of Worcester

advertisement
Learning to Program
Essential skills to code in Python for KS3 & KS4
Saagar Jagatia
1|Page
Candidate: 10003313
Release Information and Copyright Notice
© This material is subject to copyright. You are free to use this for your own personal use and for
other teachers within your institution, including photocopies to those. You may not copy, photo-copy
or e-mail this document to parties outside your institution. The University of Worcester logo and
related trademarks may not be used without permission directly from the University.
The information contained in this resource pack are from sources believed to be reliable. However,
because of the possibility of human or mechanical error by our sources I cannot guarantee the
accuracy, adequacy or completeness of any information. Readers should also be particularly aware of
the fact that the internet is an ever-changing entity. Some facts may change once this book is released.
The software used throughout this pack may be upgraded by the developers, which may alter your
experience of the language and the software packages.
Release: SHJagatia;
06th November 2012, Draft 1.
11th December 2012, Draft 2.
16th January 2013, Draft 3.
28th February 2013, Final Draft.
2|Page
Candidate: 10003313
Table of Contents
Learning to Program ................................................................................................................................ 1
Release Information and Copyright Notice.............................................................................................. 2
Table of Contents ................................................................................................................................... 3
Forward .................................................................................................................................................... 6
Preface ..................................................................................................................................................... 7
My Project Mission .................................................................................................................................. 9
Acknowledgements.................................................................................................................................. 9
Intro 1a. How To Use This Book ............................................................................................................. 10
Working through the sections ........................................................................................................... 10
Code Examples ................................................................................................................................... 10
Intro 1b. Programming in School ........................................................................................................... 11
Logo .................................................................................................................................................... 11
Scratch................................................................................................................................................ 13
Intro 2. Learning and Teaching how to Program ................................................................................... 14
Modification (Modding) ..................................................................................................................... 14
Extension ............................................................................................................................................ 14
Collage................................................................................................................................................ 14
Reading Code ..................................................................................................................................... 15
Coding from Scratch........................................................................................................................... 15
Intro 3a. Introduction to Software Development .................................................................................. 16
Iterative Development ....................................................................................................................... 16
Professional Iterative Software Development ................................................................................... 16
Debugging .......................................................................................................................................... 16
Intro 3b. Strategies for Debugging in Python ........................................................................................ 17
Syntax Errors ...................................................................................................................................... 17
Debugging Example............................................................................................................................ 18
Intro 4. Introduction To The Python Language ...................................................................................... 19
Downloading, Installing, Configuring and Running Python ............................................................... 19
Let’s begin. ......................................................................................................................................... 22
Official Python Cheat Sheet – for a real head start with the language ............................................. 23
Now some Python Basics ................................................................................................................... 24
TECHNICAL STUFF: ............................................................................................................................. 25
Some Rules and Information ................................................................................................................. 27
3|Page
Candidate: 10003313
Naming Rules ..................................................................................................................................... 27
Python Data Types ............................................................................................................................. 27
Modules ................................................................................................................................................. 28
Comparing Strings .............................................................................................................................. 29
TECHNICAL STUFF: ............................................................................................................................. 29
The Three Ds ...................................................................................................................................... 29
Lesson 1. Lets Dive Into The Code ......................................................................................................... 30
Example 1: Numerical Input.py .......................................................................................................... 30
Example 2: GuessTheNumberBySaagarJagatia.py ............................................................................. 32
Example 3: HangmanBySaagarJagatia.py .......................................................................................... 33
Lesson 2. Understanding the Python Library: ‘Import’ & Creating Modules......................................... 39
Using & importing Modules ............................................................................................................... 39
Creating Modules ............................................................................................................................... 40
Lesson 3. Understanding a Created Library ........................................................................................... 41
Graphical Outputs ............................................................................................................................ 41
Lesson 4. Tkinter an Introduction .......................................................................................................... 43
Here is a Complete Example .............................................................................................................. 44
Features of Tkinter ............................................................................................................................. 44
Example 1: Helloworld.py .................................................................................................................. 45
Example 2: SimpleCalculator.py......................................................................................................... 46
Tkinter in school:................................................................................................................................ 47
Tkinter Widgets Table ........................................................................................................................ 48
Font Style Options.............................................................................................................................. 48
Tk Option Data Types ......................................................................................................................... 49
Lesson 5. PyProcessing an Introduction ................................................................................................ 51
Example 1: PyProcessing .................................................................................................................... 54
Example 2: Helloworld.py .................................................................................................................. 55
Example 3: Helloworldrot.py ............................................................................................................. 56
PyProcessing Questions and Challenges ............................................................................................ 57
Pyprocessing in school: ...................................................................................................................... 58
Pyprocessing Variables ...................................................................................................................... 59
Structure .......................................................................................................................................... 59
Image................................................................................................................................................ 59
Environment..................................................................................................................................... 60
Colour ............................................................................................................................................... 61
4|Page
Candidate: 10003313
Shape................................................................................................................................................ 62
Input ................................................................................................................................................. 63
Math ................................................................................................................................................. 65
Transform ......................................................................................................................................... 65
Lights, Camera.................................................................................................................................. 66
Camera ............................................................................................................................................. 67
Pyglet Package – Extension task ........................................................................................................ 68
Lesson 5: Python Challenges Questions................................................................................................. 71
Python Challenges Answers ................................................................................................................... 72
Appendix – Code Snippets ..................................................................................................................... 76
Debugging .......................................................................................................................................... 76
Python Basics - Maths ........................................................................................................................ 76
Python -
Example 1: Numerical Input.py ...................................................................................... 76
Example 2: GuessTheNumberBySaagarJagatia.py ............................................................................. 77
Example 3: HangmanBySaagarJagatia.py .......................................................................................... 78
Tkinter -
Example 1:HelloWorld.py .............................................................................................. 82
Example 2: SimpleCalculator.py......................................................................................................... 83
PyProcessing -
Example 1:PyProcessing.py.................................................................................... 84
Example 2:HelloWorld.py .................................................................................................................. 85
Example 3: HelloWorldRot.py ............................................................................................................ 85
Something fun for class...................................................................................................................... 86
1 player pong ..................................................................................................................................... 86
References ............................................................................................................................................. 89
5|Page
Candidate: 10003313
Forward
This resource pack was written as part of an independent study during a third year degree course at,
the University of Worcester. This resource pack contains information to assist the drive towards
concepts and skills allied to Computer Science, and its introduction into the secondary school
curriculum at KS4 (GSCE) level.
This book will focus on the Python programming language. Following a meeting with the regional
organiser of CAS (Computing at Schools) group and Dr, Colin B Price of University of Worcester, there
was a mutual feeling that Python is a useful language to introduce to KS4 level pupils to prepare them
for further Computing Studies beyond school, (KS5). In order to test this theory, this book will aid the
research to see how KS4 pupils respond to the Python language, and whether or not it is an
appropriate programming language at the KS3/KS4 level.
This piece of work is aimed at teachers and maybe their pupils. It will guide teachers on how to use
Python within their classes.
S. H. Jagatia.
University of Worcester (2012-2013)
6|Page
Candidate: 10003313
Preface
This piece of work aims to introduce the Python language to Year 10 - 11 students. The projects’
mission is to develop teachers and students coding capabilities, and also to help them learn how to
program creatively. It is directed to the teachers, to help you craft lessons for your students at this
level.
Teacher Assumptions:
 You have never programmed before, or have had minimal exposure to programming
 You are intelligent and motivated, and have great experience and knowledge with computers
 You are able to use a text editor, if not your colleagues should provide a brief tutorial –
(installation guide will be provided: Notepad++, Python’s IDLE)
 You know little or nothing about Python and its capabilities
Student Assumptions:
 You have never programmed before, or have had minimal exposure to programming
 You have a personal drive to do well
 You are intelligent and motivated, and have experience and knowledge of using and
understanding computers
 You are unable to use a text editor, if not your teachers should provide a brief tutorial –
(installation guide will be provided: Notepad++, Python’s IDLE)
 You know little or nothing about Python and wish to learn more
I, Saagar Jagatia, present you with ideas and suggestions on how to teach programming in your
lessons, but do not provide you with ‘lesson plans’ but more of a tool for learning.
This resource pack can be used as a standalone introduction at KS3 & KS4, or also in preparation for
GCSE classes. There are various sections to the book, it includes: ‘Intro’s’, ‘Projects’, ‘Lessons’ and
‘Questions’.
The intros are aimed at you and are intended to get you started, by providing a little background of
the concepts which will be discussed in later sections. The projects and the questions will allow you to
practice and extend your Python skill set. In the lessons section, you will be given general pointers on
how to craft a sequence of lessons to teach your students
The pack will look at a variety of variable types: integer, real, Boolean, character and string, all these
terms and concepts will be introduced and discussed.
7|Page
Candidate: 10003313
You may or may not have heard of ‘Object Oriented Programming’ (OOP). It is a sophisticated and
natural approach to writing code. It is a set of tools and methods that enable software engineers to
build reliable, user friendly, and maintainable, well-documented, reusable software systems that fulfils
the requirements of its users. Python is an extensible, object-oriented interpreted programming
language. An Object-Oriented programming language provides support for the following O-O
concepts:
 Objects and Classes
 Inheritance
 Polymorphism and Dynamic Binding (The ability to create a variable, a function, or an object
that has more than one form)
In addition there are many other modules available from third parties providing many other services.
Python is licensed under terms similar to the LGPL license (2007) and is available for: Linux, Unix,
Windows and Macintosh operating systems.
More information on Python is available at www.python.org.
The primary author of Python is: Guido van Rossum;
E-mail: guido@python.org
This resource pack has been created with information which has been collated over several years’
research on how best to teach programming to pupils. This resource pack will undergo several stages
of evaluation from teachers and pupils. My understanding of how best to teach pupils is summarised
below:
 Programming must be creative rather than problem-solving.
 The results of student’s code should be visual, involving shapes, colours and lines.
 Students should be given advice and assistance, when executing code.
 Students should be able to write interactive code, whereby the programs can be influenced by
the use of a mouse, and a keyboard.
 Never give student a sample of incorrect code, and ask them to find errors. Students should be
given ‘Code Snippets’ this will assist them in learning what it can actually do.
8|Page
Candidate: 10003313
My Project Mission
”During my personal School/ Sixth Form education, I was never faced with Computer Science and
Programming in particular. University on the other hand, required me to know the basics at least (to
get by). Without prior programming experience I had to learn independently.”
“Hence, this resource pack has been developed for pupils and teachers who wish to drive Computer
Science into the curriculum. This drive could potentially change a child’s computer education”
Acknowledgements
Writing Python Programming has been the collective effort of many people. Each of these persons
in a way contributed their expertise and effort to help make the book more effective.
Hence, this resource pack has emerged as part of a third year independent study. I would like to
take this opportunity to thank: Colin Price, John Palmer, the teachers who will review the finished
piece, my friends, family and finally the Python documentation available online. All of which have
helped radically to develop this resource pack. They provided comments that resulted in
significant improvements to both the quality and depth of the work.
Some of the code examples used within this pack have been derived from coded programs
written by others, all available via ‘open source’ documentation online. During the development
of this resource pack, I personally was learning to program using Python, and without the use of
the documentation online the learning process may have proved far more difficult.
9|Page
Candidate: 10003313
Intro 1a. How To Use This Book
Working through the sections
This resource pack is categorised into intros, and lessons, each looking at something new, however
some may refer to chapters earlier in the pack. It is advised to follow each chapter in a linear path in
your teaching and learning. By following each section the desired outcome is that, teachers, students
and pupils will have gained an understanding and also built confidence which will allow them to code
creatively and independently. Learning is all about exploring. If you can put it into your pupil’s minds
that they are in control they will grasp the opportunity to learn beyond the classroom walls.
How a section may be structured:

An introduction
 Some sample code (Print screens, copy and paste version will be available in the appendix)
 Project
 Random questions for further development
 Several sources may be used to back up information that is stated.
o
Including web links whereby you can enhance your studies
Code Examples
The code used in the screen shots will be available in the ‘appendix’ section. In the appendix section
the code that creates specific program can be easily read and reused (if desired).
10 | P a g e
Candidate: 10003313
Intro 1b. Programming in School
Currently schools tend to use simple programming languages within lessons, two popular ones
are: Logo and Scratch. Hall Green School (A school placement I attended), situated in Birmingham,
UK currently use both of these software tools.
Several year 7 classes were being taught how to use Logo during my placement, this proved to be
an extremely interesting experience as I was able to see how different teachers taught and helped
their classes grasp their introductions to programming.
All three of the teachers had different approaches to delivering the lesson, the teaching styles
proved successful, and many of the class members were able to understand the tasks which were
being showed to them.
The lesson was made up of:
1.) An introduction to what will be taught and learnt. (Lesson Objectives)
2.) A run through of the software
3.) A simple introductory task sheet, which had basic commands.
4.) Finally a challenge sheet, which was given to the more able children.
I found that the key to teaching programming to a young audience is that the teacher must put
confidence into the pupil’, and ensure they have total faith in their own ability. Along with this
make sure all pupils know what is required of them and state what they must do to accomplish
the task.
Logo
Available at: http://el.media.mit.edu/logo-foundation/
Logo or ‘Win Logo’ is increasingly being used within schools, both primary and secondary. This
language in particular is good for giving young children an introduction to the world of computers
and programming. Children that have some knowledge about programming are better suited to
furthering their computing capabilities in future years of educational development.
Logo was originally conceived and written as a functional programming language which drove a
mechanical turtle as an output device. Seymour Papert invented Logo in 1967 with the help of
Wallace Feurzeig, Goldberg (1991), Massachusetts Institute of Technology (2012). Since then the
use of ICT and computer science within schools has excelled beyond belief. Papert’s earlier work
had shown that computers can also be manipulated in into producing creative outputs, which
now is being utilized for students grown up in the digital age.
11 | P a g e
Candidate: 10003313
"Logo is the name for a philosophy of education and a continually evolving family of programming
languages that aid in its realization."
- Logo created by Papert helped develop Computational Science which is now a colossal part of
modern education.
-Abelson H, Logo Foundation (2012)
Logo has been a historical turning point for the way in which children have experienced and
explored computers and their many capabilities; logo is used mainly in early-years education for
mathematics. The Logo Foundation is still running and developing ways to improve child
interaction with computers.
A turtle application is available in Python. (Just like Logo)
Basic commands:
[
>>> import turtle
>>> t = turtle.pen()
- importing the module
- creates a canvas
>>> t.forward(50)
- turtle moves forward
>>> t.backward(50)
- turtle moves backwards
>>> t.left(90)
- turtle moves left
>>> t.right(90)
- turtle moves right
>>> t.up()
- turtle moves up
>>> t.down()
- turtle moves down
>>> t.reset
- erases the canvas and puts turtle in the starting position
>>> t.clear
- clears the screen and leaves the turtle where it is
]
Project
Try to create a square, and then move onto creating a more exotic shape. – try a star
12 | P a g e
Candidate: 10003313
Scratch
Available at: http://www.scratch.mit.edu.
Scratch is another popular programming tool which is used in schools today. It is a programming
language developed at the MIT Media lab. It offers users a visually appealing environment, which
allows novice programmers (your students) to learn programming without initially having to write
syntactically correct code.
Users can:
 Create games
 Write interactive stories which also use animation
Scratch has the potential to develop an individual that is learning how to program, however much
of its benefit lies with the inquisitiveness of the learner and their capacity to explore and plat with
programming constructs. The software programs 2-D graphical objects, users write scripts (drag
and drop command) and make them interact with one and other. The Scratch application allows
users to import images and sounds, apart from creating their own media, to make media-rich
projects.
Scratch is clearly a programming language for beginners as it has a minimal set of language blocks
and command set with an easy to use application interface. The colour-coded commands are
categorized by their functionality and are presented in panes on the same window. This way the
users are always looking at the commands and hence it is highly probable that they can enhance
their projects better by using additional commands and constructs. By not having distinct compile
and edit phases, Scratch programming is easier for users as they can change their program while it
is running and can test program fragments to see what they do. It is most definitely a great
programming tool for young novice programmers.
Scratch programming also encourages sharing and learning across peers. The Scratch Website
allows easy sharing of projects, that makes collaboration and receiving feedback simple. Scratch
also supports the 21st century learning skills: information and communication skills, thinking and
problem-solving skills, and interpersonal and self-directional. – Lodha and Somyalipi (2013)
13 | P a g e
Candidate: 10003313
Intro 2. Learning and Teaching how to Program
Your students who are learning to code may expect that you will ask them to write programs from
scratch (no pun intended). But you should never do this, since this is not how professional
programmers work. Programmers may have to create or maybe even amend a program with code that
already exists. A company may require a programmer to integrate and augment two types of code
together. That means building on existing code.
It is recommended to teach your pupils to program in a professional manner. So how do we get our
students to behave like a professional programmer? There are several approaches I suggest to you.
Modification (Modding)
Give your students some code and invite them to change the value of a variable, and to reflect on the
consequences. This will help them to understand what the variable does and therefore means. For
example perhaps your example creates a specific code string of sentences, allow your students to do
the same but ensure they use different string values, so they can see the consequences.
Or for a graphical example allow your students to view code for a canvas you may have programmed
and allow them to change the variables (maybe the speed or size of various objects). In doing a
challenge like this they only need to change a small number of lines in the code you have given them.
Extension
Here, students are invited to extend a given program. Take the ‘Hangman’ game on page33 for
example. You may have given your students this code and told them to extend the game, maybe add
words or change the theme of the game totally. (To something more appropriate for them)
If for example you wanted to give an example of the Pyprocessing module; you could invite them to
create a program that includes text with animation. You could invite them to change the colour of the
canvas and text. How you figure this out is up to you, but please remembers the code examples
provided for you in this book are minimalist and are useful starting points for extension. Also some of
the code examples are natural extensions of previous examples.
Collage
Collage means “cutting and pasting” and in this context of programming it involves combining various
elements of other peoples’ code to make our code work. While this is a legitimate programming
practice, it is fraught with dangers for our students at this level. The more lines of code your students
copy will increase their debugging efforts and therefore will lead to frustration. The best way to use
collage is to copy and paste some standard functions, into the student code, such as how to change
the size of an image within a canvas. Or if the program is text based, just collage small portions of the
text.
14 | P a g e
Candidate: 10003313
Reading Code
Here, in your teaching, you should provide your students with an “off-PC” activity, and maybe get
them into small groups. You will give them a paper-based activity which consists of some code and the
visualisation of this code, e.g. as a series of coloured shapes. You will invite them to read the code and
(through a discussion) explain how this code produced the realised visualisation. (Please note this
should be done with more able pupils) Again this is professional programming practice where software
engineers must read the code of their colleagues before they can contribute to the project.
Coding from Scratch
Most professional programmers do not start from scratch, at least they are provided with a
“template” and some “libraries” which they can use, many are available via the Python documentation
online and many can be searched for via Google.
However, there are some occasions where we may ask our students to code from scratch. So how do
we guide them in doing this? One way is to start by writing comments (lines preceded by #’s) to
explain the stages in their program. These comments can be useful to build up the structure of a
program, especially its logic and flow. Once the comments are complete, the student can begin to
write code following each comment, so the final program emerges. Another useful approach is to
identify which functions are needed to get the whole program working, without focussing on coding
these functions in that initial stage. Several good example of this is shown throughout this resource
pack. Yet I advise caution in using this approach at KS3/4 level.
15 | P a g e
Candidate: 10003313
Intro 3a. Introduction to Software Development
Once your students have followed your material based on the topics presented in this learning
resource, they will hopefully experience a creative and fun situation where they are asked to code
some short programs with minimal guidance (based on how they have adapted to programming). In
general, they will succeed with these short programs and hopefully they will have an intrinsic
motivation to continue.
When they turn to the Projects they will experience a different situation since they will need to
combine various coding techniques and also various concepts. As their code increases in length, so will
their opportunity to make mistakes. The number of errors they will make (known as “bugs”) will
increase. Yet we can turn this around into an educational experience. Making mistakes is how people
sometimes learn.
This is exactly what happens within the software industry where programmers code, make mistakes
and learn from them. So how can we support our students in this “growing-up” phase? Let’s have a
look.
Iterative Development
Iterative development acknowledges that a coder may not write a complete program that works
immediately. The program may give errors and the coder will need to have one or more attempts at
coding to correct these until the program finally works. The coder’s attempts of creating a program
(perhaps 2 or more) are iterations, a series of trial-and-error experiences to getting the code to work.
Professional Iterative Software Development
Here there are many models of software development but there are some emergent common themes,
analysis, synthesis and evaluation, but which are often situated within the iterative context. In the
analysis phase, the programmer finds out the requirements of the program and this leads to a
program specification. In the synthesis stage, the code is written but this may also include paper
sketches such as flow charts of pseudo-code. In the analysis phase, the results of the working code are
evaluated. Perhaps there is need to refine, and so the synthesis stage is entered again. Or perhaps the
goals of the project need to be changed, in which case the analysis stage is entered again.
Debugging
When your students start to program, they will experience bugs. To see these and to know how to fix
these bugs is an important learning experience. However, fixing these bugs has to be fast; otherwise
your students will disengage. By fixing bugs your students must also learn something about how to
code, whether syntax or perhaps program logic. Remember students learn from mistakes. Your
support as a teacher of Computing is crucial here, you cannot expect your students to ‘go online’ to fix
their bugs; this is both inefficient and frustrating for your students. So you must really know the
language you are teaching, and you must know any example code you give to your students inside out.
16 | P a g e
Candidate: 10003313
Intro 3b. Strategies for Debugging in Python
When we write programs, often they do not work; we say they contain a ‘bug’. There are two sorts of
bugs; those which do not allow the program to compile and those which cause the program not to
execute properly. Your novice programming students will encounter the first sort fairly often, since
they are learning the syntax of the language at the same time as using the language to create
something. We refer to these bugs as syntax errors, and they will be flagged up by Python’s IDLE when
your students try to run the program (F5 or ‘Run’ on the menu bar). If a program has syntax errors,
then it will not run. So these errors will need to be corrected first.
However not all bugs are syntax errors, indeed when a program contains no syntax errors and
compiles successfully, there is no guarantee that it will run as intended. This may be due to the
program containing logical errors, but also because your student has misunderstood the code. We
refer to these as perceptual errors.
Syntax Errors
Your students will probably make some of these common errors.
Incorrect Code
Error
Correct Code
PRINT “hello
world”
print "hello
World"
str( input("What
is your guess? ")
23-48'
SyntaxError: invalid syntax
print “hello world”
Python
Version
2.x
SyntaxError: invalid syntax
print("Hello World")
3.x
SyntaxError: invalid syntax
str(input("What is your
guess? "))
23-48
3.x
SyntaxError: EOL while
scanning string literal
2.x
3.x
Python attempts to locate any syntax errors and highlights the error. When an error is pointed out
Python gives the line number of the incorrect code, which is an absolute god send when debugging
your program. This is especially true for missing semi-colons and brackets, as it is a strict language.
Python has its own integrated debugger. It is a module known as pdb (Python DeBugger).
17 | P a g e
Candidate: 10003313
Please visit ‘Intro 4’ to view details on how to download and install Python.
Debugging Example
Lets create a simple program, in which you can set pdb to trace your code;
Now execute
As you trace your program you should only really need to go through it to check your lines of code. In
order to go through code press ‘n’ and enter (on your keyboard)
More information on pdb is available directly at python.org http://docs.python.org/2/library/pdb.html
Intro 3 adapted from Source: Price (2012)
18 | P a g e
Candidate: 10003313
Intro 4. Introduction To The Python Language
This chapter will kick-start your work with Python. You will learn how to download, install and
configure Python and Notepad++.
Downloading, Installing, Configuring and Running Python
Python and its documentation are made available at the following: http://www.python.org/ it is freely
available to download at the following link http://www.python.org/download it is a multiplatform
language. If you are using Windows choose ’Windows’ download. This resource pack will be using
screen prints from Python 3.3.0.
Once the appropriate selection has been made the download will begin, once downloaded open up
the file. Follow the installation steps.
The print screen below shows the location of Python on my computer, it is advised to save it onto your
computer hard drive, and in a folder of its own. My copy is located in C:\Program Files(x86)\Python3.
Python is just over 50 MB.
19 | P a g e
Candidate: 10003313
There are numerous text editors out there; however, I will explain the use and installation of two
potential text editors; Python’s IDLE, and Notepad++.
Firstly Pythons IDLE (Integrated Development Environment); this text editor is designed specifically for
Python. It is downloaded with the Python software package. It is written in Python and the Tkinter GUI
toolkit. Tkinter will be explained later.
According to the included README file, its main features are:
 Multi-window text editor with syntax highlighting, auto completion, smart indent and other.
 Python shell with syntax highlighting.
 Integrated debugger with stepping, persistent breakpoints, and call stack visibility.
It can be found in the Python’s sub-folders: C:\Program Files(x86)\Python3\lib\idlelib
Or a simple search can be done using the start menu. Once located a Python Shell will open, this is
where written executable code is ‘run’. The shell enables small (single line(s)) snippets of code to be
executed. To begin writing programs and exploring the language, click on ‘File’, and ‘New Window’.
Project
Why do you think Python and IDLE are named as they are? Why not try to find out...
20 | P a g e
Candidate: 10003313
Secondly Notepad++; Notepad ++ is a popular text editor, it is specifically designed for Windows and
used by many professionals. It is not designed for just Python programming; it can be coded using
many different languages it is lightweight (5.5MB) and robust. If you are new to the world of
programming, it is advised you stick to IDLE for Python.
The latest version is 6.2.2. Below are details of how you can download and install Notepad++.
Notepad++ can be downloaded directly fromhttp://notepad-plus-plus.org/download/v6.2.2.html.
Once the link [
] is clicked your download will shortly begin.
Follow the installation steps on screen, Agree to the terms and conditions, choose your destination
and root folder for the software, select all of your required components (as above) and create an
easily accessible desktop shortcut. Below is a screen shot of Notepad++, it shows all of the
introductory information. To begin programming, click on ‘File’ then ‘New’ here you have your new
clean window.
This resource pack will focus mainly on Pythons IDLE. However if you opt to program with Notepad++
there is plenty of documentation out there.
21 | P a g e
Candidate: 10003313
Let’s begin.
Click and open IDLE. We’ll start with something simple. Traditionally the first program you write in a
new language is called “Hello World” in python the first step is to open up a ‘New Window’ from the
Python Shell and type:
Print (“Hello, World!”)
N.B. Take note of the Brackets (-) not all versions of Python use bracketed code – as you will later see.
Below are steps taken to create the program, to execute it press F5 once saved. If a file is not saved it
will not load.
Congratulations you have completed your first piece of Python coding.
Project
Now you try to create a few strings of code. – remember to refer back to the examples.
22 | P a g e
Candidate: 10003313
Official Python Cheat Sheet – for a real head start with the language
23 | P a g e
Candidate: 10003313
Now some Python Basics
It is best to learn some of the basics before we move onto the more attractive graphical outputs.
Once Python starts running in interpreter mode, using IDLE or a command shell, it produces a prompt,
which waits for your input. For example, this is what I get when I start Python in a command shell on
my version of Windows:
[
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48)
[MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license
()" for more information.
]
The easiest way to get started is to run Python as an interpreter. In the interpreter you type the
command and Python produces the answer. The example I present will replicate the functions on a
calculator. To begin open up ‘IDLE’ Python Shell will work fine for this task as we are just executing
single lined commands.
Arithmetic Operators:
Comparison operators:
Plus (+): Addition
less than (<)
Parentheses (()): Grouping
greater than (>)
Asterisk (*): Multiplication
equal to (==)
Forward Slash (/): Division
not equal to (!= or <>)
Double asterisk (**): Exponentiation (x to the
power of y)
24 | P a g e
Candidate: 10003313
Try something else with the numbers, have a little play around. For example, to try and get a list of
square numbers of 2; type:
The mistake above with the first command was placed purposefully, so you are able to see the
strictness of the Python language. All syntax used must be correct before the interpreter is able to give
an answer and when writing longer programs all indentation used must be correct. These are all issues
that can be overcome with a lot of time and practice.
TECHNICAL STUFF:
“In Python, a name refers to an object. A name is actually a label for a memory location in the
computer that stores something—a value, a chunk of code, or any sort of thing Python
understands. All these "things"—anything that's stored in a memory location—are called objects
in Python. Therefore, Python programmers often say that when you enter a statement such as x =
5 in Python, you are binding a name (x) to an object (5). You can have multiple names for the
same object.” –Maruch, (2006), Python for Dummies.
25 | P a g e
Candidate: 10003313
Below is an Example of what assigning ‘Names’ to a value does. A name can vary in size and
length. The example below is a sentence.
Example: If you want to assign the sentence ‘Hello World, I am beginning my journey into Python
Programming’ to ‘X’ you would type:
[
x= (‘Hello World, I am beginning my journey into Python Programming’)
]
When you type in ‘x’ to the interpreter the sentence will be displayed.
Below is an example I created. Where:
x = ‘Hello, my Name is Saagar’
y= ‘Saagar is trying to help with your understanding of the Python Programming Language’
It is possible to alter/edit your ‘Names’ and the Values within them. You can overwrite them at
any time too. If you wanted to add something (for example to add my surname) to the name ‘x’
with the value of ‘Hello, my Name is Saagar’ you would type:
[
>>> x= (“Hello, My Name is Saagar”)
>>> y= (“Saagar is Trying to Help with Your Understanding of the Python
Programming Language”)
>>> j= (“ Jagatia”)
>>> x+j + (“, “) +y
]
26 | P a g e
Candidate: 10003313
It is important to leave a space (‘ ’) before ‘ Jagatia’ so that when the code executes there is
space in the between Saagar & Jagatia. This example is shown below in the interpreter.
Some Rules and Information
Naming Rules
You can use any names you want, as long as they follow these rules:
 Names must start with either a letter or an underscore character (_ ).
 You can't use any of Python's reserved words or keywords.
These are words that have specific meanings to Python, such as if (which begins an if statement).



Names are case-sensitive. num is different from NUM and nUm. – As shown in the a screenprint
above
By convention, most Python programmers use lowercase for names that stand for values.
They use other rules for names that stand for functions and classes—you can find out more
about these conventions in later chapters.
It's a Good Idea to use meaningful names. If you name everything with a single letter, for
example, you may have trouble remembering what the name stands for later.
Python Data Types







Numbers – data you would use to do math with.
Class - are useful because they can combine both data and methods that operate on that data
Modules – is a text file that can contain any kind of Python code
Strings – are for text characters and for binary data.
Sequences – are for lists of related data that you might want to port and merge.
Dictionaries – are collections of data that associate a unique key with each value.
Sets – are for doing set operations (finding the intersection, difference and so on) with
multiple values.

Files – are for data that is or will be stored as a document on a computer.
27 | P a g e
Candidate: 10003313
Modules
A module is a text file that can contain any kind of Python code, but a module usually organizes tools
that work in a particular way. Sometimes it also includes names that store particular values. You can
make a module available to another program by importing it. Modules are the key to Python’s
portability and power. Python itself is built up of modules.
To import a module:
>>> import math
Once the module is imported you can utilize the information within it.
Example; to work out what pi is:
>>>math.pi
3.141592653589793
[Image from: Python Basics: Doty. S, (2008)] - http://anh.cs.luc.edu/331/notes/PythonBasics.pdf
28 | P a g e
Candidate: 10003313
Comparing Strings
When you're working with numbers, it's usually obvious what the smallest and largest numbers are.
But it's less clear what smallest and largest mean when you're talking about characters.
TECHNICAL STUFF:
A character's ASCII or Unicode value (a number) determines the character's order. So it would also be
correct to talk about one character coming "before" (smaller) or "after" (larger) another character in a
numbered list of characters. The following list describes how Python orders (assigns sizes to)
characters:
 Letters at the beginning of the alphabet are smaller than letters at the end.
A is smaller than Z.
 Capital letters come before (are smaller than) lowercase letters.
Y and Z are both smaller than a.
 Digits are smaller than letters.
5 is smaller than A.
 Most punctuation marks come before digits or letters.
! Is smaller than 5. The exceptions are curly braces ({}), the pipe character (|), and the
tilde (~), which are larger than letters.
To determine which of two strings is larger, use the < and > operators.
The Three Ds
If you're writing a program that's more than a few lines long, don't just sit down and start coding. You
need to take three steps to make your program the best it can be. These are the three Ds: - Maruch
(2006, P.65) Python for Dummies

Document: Making sure others can read your program

Design: Making sure your program is solving the right problem and is organized so that it's
efficient and potentially reusable

Debug: Making sure your program doesn't have any mistakes in it and that it responds
appropriately when given wrong input
29 | P a g e
Candidate: 10003313
Lesson 1. Lets Dive Into The Code
Example 1: Numerical Input.py
I am going to take you through steps to code a simple calculation program. It is a program to calculate
the area of a Rectangle or a Square.
So to begin, open up the Python Shell, open up a ‘New Window’. It is always best to leave some
introductory information on the program when you begin creating like so;
The code for the program is copy and pasted below, once you have read and understood it, try to
interpret it and change some of the code snippets. Maybe change the information completely and add
new shapes, remember you must know the calculations before you attempt to code math.
Numerical_Input.py
30 | P a g e
Candidate: 10003313
31 | P a g e
Candidate: 10003313
Example 2: GuessTheNumberBySaagarJagatia.py
I am going to take you through steps to code a simple game. It is a number guessing game!
So just like before, open up the Python Shell, and open up a ‘New Window’. Leave some
introductory information on the program when you begin creating like so;
GuessTheNumberBySaagarJagatia.py
32 | P a g e
Candidate: 10003313
Example 3: HangmanBySaagarJagatia.py
I am going to take you through steps to code a simple game. It is a replication of the popular
school game, Hangman.
So just like before, open up the Python Shell, and open up a ‘New Window’. Leave some
introductory information on the program when you begin creating like so;
The code for the program is copy and pasted below, once you have read and understood it, try to
interpret it and change some of the snippets around. Maybe change the information completely.
N.B. Remember Google is a powerful tool; it may be a good idea to befriend it! Much of the
Python documentation can be summoned using the Google search engine.
33 | P a g e
Candidate: 10003313
HangmanBySaagarJagatia.py
34 | P a g e
Candidate: 10003313
35 | P a g e
Candidate: 10003313
36 | P a g e
Candidate: 10003313
This is all the code required to create the Hangman game. It is fully functional on Python 3.3.0 –
The code can be found in the appendix section.
37 | P a g e
Candidate: 10003313
Bear in mind Python is strict! So you must take care when coding, simple errors can create
massive disruptions. Also take into account the indentation of the code and the use of special
characters like: ( ) [ ] “ “ = #. The results of the program are presented below. Remember to
execute (run) a program press ‘F5’ or using the navigation bar.
This is a screen print of the game in the Python Shell; you can see that the interpreter can pick up
on mistakes with letters.
Your turn!
Project
Try to experiment with the language, try creating your own game, or a piece of interactive text. If you
require more aid or wish to enhance your knowledge visit http://www.python.org/doc/. Here you will
find many useful links to documentation.
38 | P a g e
Candidate: 10003313
Lesson 2. Understanding the Python
Library: ‘Import’ & Creating Modules
Using & importing Modules
As previously stated, Python is built up of modules. Dayley (2006) stated, these modules that make up
the language are Python files. Modules can be created and altered to suit your program requirements,
however this is only recommended for those who are comfortable with using it. Large applications or
libraries that incorporate several modules are typically bundled into packages. Packages allow several
modules to be bundled under a single name, Dayley (2006).
Modules can be loaded onto your Python program using the ‘import’ statement. When it is imported,
the program can be capable of executing functions and strings etc. All of the objects within the
imported module’s source file become available. More than one module can be imported in the same
statement; although the Python Style Guide recommends not to-do this instead the programmer
should write for example;
[
import math
import cmath
]
To import a portion of a module, you must define ‘from’ (which is the parent module) and what you
wish to ‘import’. Example;
[
from math import sin, cos
]
When a module is introduced using the ‘*’ annotation it means all of the attributes from this module
will be imported into the program. Example;
[
from math import *
]
This information was acquired using a study undertaken by Fangohr (2012, p. 69-71)
In Python 3.3, importing a module takes a per-module lock. This correctly serializes importation of a
given module from multiple threads (preventing the exposure of incompletely initialized modules),
while eliminating the aforementioned annoyances, Pitrou (2012).
Python has great documentation available online from http://python.org/ and it is possible to gain
access to modules created by third parties via this link:
http://pypi.python.org/pypi?:action=browse&c=533&show=all. However before you attempt to use
one of them you should make sure are comfortable downloading them and using them. As the
language is open source and anyone can post a module on the website, not all are as useful as the
others.
39 | P a g e
Candidate: 10003313
Creating Modules
A module is in principle nothing more than a Python file. (.py) this is an example of a module file which
is saved in module1.py:
[
def someusefulfunction ():
pass
print (“My name is “, __name__)
]
Once it is executed (f5) or ‘Run’ the file shows up on the shell, once it does to print the file name
‘import module1’
Your turn!
Project
Now try and create a module of your own and import it.
40 | P a g e
Candidate: 10003313
Lesson 3. Understanding a Created Library
The file shown in this lesson was altered by Dr. Colin Price of The University of Worcester. Dr. Price
had been looking at a programming language called ‘Processing’, and his aim with was to give Python a
graphical output a little like that of ‘Processing’.
Processing is not important right now but this pack will later be reviewing PyProcessing –which is
Pythons adaptation of the language.
Graphical Outputs
41 | P a g e
Candidate: 10003313
Project
Now try to create a basic library of your own, or type out the one above and extend it.
N.B. Do not forget to use Google as a research tool – it may prove to be a powerful developer’s tool.
42 | P a g e
Candidate: 10003313
Lesson 4. Tkinter an Introduction
http://docs.python.org/3.0/library/tkinter.html - Further research.
Most Tkinter programs work on Python 3.x, the examples used within this pack will be from using
Python 3.3.0. Shipman (2013), stated that Tkinter is a GUI (graphical user interface) widget set for
Python. Tkinter was programmed and coded by Fredrik Lundh in 1999. The Tkinter (Tk Interface) is the
standard Python interface to the Tk GUI (Graphical User Interface) toolkit. Both Tk and Tkinter are
available on most UNIX, Macintosh and Windows platforms. It is vital to remember Pythons sensitivity,
remember that Python requires indentation, and is case sensitive.
For further information please Visit: http://www.pythonware.com/library/tkinter/introduction/whatstkinter.htm or http://wiki.python.org/moin/TkInter
N.B. Please do not mix Tkinter up with Pyprocessing or Pyglet. Watch out for the capitalisation of some
of the words within the code, and remember to save the file with the suffix ‘.py’
Grayson (2000) suggests that Tkinter and Python have the ability to deliver viable applications. Tkinter
is ‘imported’ just like any other module. As shown on page 28. Tkinter comprises of a number of
components. Tkinter includes a number of Python modules. The two most important modules are
the Tkinter module itself, and a module called Tkconstants. The former automatically imports the
latter, so to use Tkinter, all you need to do is to import one module: Which is:
[
import Tkinter
]
OR
[
from Tkinter import
]
If it fails with "No module named _tkinter", your Python configuration needs to be modified to
include this module (which is an extension module implemented in C). Do **not** edit
Modules/Setup (it is out of date). You may have to install Tcl and Tk (when using RPM, install the devel RPMs as well) and/or edit the setup.py script to point to the right locations where Tcl/Tk is
installed. If you install Tcl/Tk in the default locations, simply rerunning "make" should build the
_tkinter extension. – Tkinter (2013)
To check whether the module has been imported correctly you could type tkinter._test() into
the Python prompt. A little window will show up (the test program)
43 | P a g e
Candidate: 10003313
Here is a Complete Example
Below is an example of code which was executed. It is a source taken from Grayson (2000)
Code comments
 First, we import components from the Tkinter module. By using from module import Label,
mainloop we avoid having to reference the module to access attributes and methods
contained in the module.
 We create a Label containing two lines of text and use the Pack geometry manager to realize
the widget.
 Finally, we call the Tkinter mainloop to process events and keep the display activated. This
example does not react to any application-specific events, but we still need a mainloop for it
to be displayed; basic window management is automatic.
Features of Tkinter
Tkinter adds OO (Object-Oriented) interfaces to TK; TK is the graphics library, Mertz (2000). According
to Grayson (2000) they are easy to read and understand, especially those who program in C++ or Java.
An important feature that TK gives to and Tkinter application is that, with a little care in selecting fonts
and other architecture-dependent features.
One important feature that Tk gives to any Tkinter application is that, with a little care in selecting
fonts and other architecture-dependent features, it will run on numerous flavours of UNIX, Win32 and
Macintosh without modification. Naturally, there are some intrinsic differences between these
architectures, but Tkinter does a fine job of providing an architecture independent graphics platform
for applications.
It is the object-oriented features, however, that really distinguish Tkinter as an ideal platform for
developing application frameworks. You will see many examples in this book where relatively little
code will support powerful programs.
44 | P a g e
Candidate: 10003313
Example 1: Helloworld.py
To begin we will code a simple ‘Hello World’ program.
(This same code will be located in the appendix section of this resource pack (Tkinter Examples))
Save the code in a folder named ‘Tkinter’ (remember its location; mine is saved in the Python root
folder.) It is best to keep all files in separate folders, maybe within sections for the modules it
covers. For examples this section is for Tkinter, so it would be best to save all code in a folder
called Tkinter.
The code above was sourced from, Lundh (1999)
Information on how to change the size of a window is shown below.
Project
Try to change the size and maybe the colour of the Tkinter applications’ window. (Research this, there
are great tutorials are available on YouTube, and great documentation can be found via a Google
search)
45 | P a g e
Candidate: 10003313
Example 2: SimpleCalculator.py
Even though the code may not look simple, this is a simple yet very effective program, Lundh (1999)
46 | P a g e
Candidate: 10003313
Tkinter in school:
What can it bring to education?
Teachers and educators may feel that the Python language may not be ideal for their classes, it may
not cater for their students needs. Tkinter, like PyProcessing and Pyglet allows users to experience
Python using a graphical window. As a teacher it is advised that you take some time out to familiarise
yourself with the basic Tkinter commands. The various Widgets, Fonts and Data Types are shown
LATER!!??!?!?!?
As an educator, you may be able to use Tkinter in year 10 – 11 classes. Year 8-9 pupils should be
taught the basics of programming using Tkinter and be given an introduction to Python (and maybe
Pyprocessing).
All programming lessons should be well planned. Lessons that are not well planned may not go as
smoothly as intended. The best thing to do would be to follow a plan:
1. Go through lesson objectives (2-5 minutes)
2. Give an introduction to the topic (Python/ PyProcessing) (5-10 minutes)
3. Set a task. (simple to begin with, then maybe a more advanced one for the pupils that can
cope) (10-15 minutes)
4. Give your students some time getting used to the code and various Syntax. (15 minutes)
o Give them some assistance with the online documentation available.
o Python - http://www.python.org/
o Pyprocessing - http://code.google.com/p/pyprocessing/
5. Round off the lesson with a few challenges, get the pupils into groups (and work on one
machine) (10minutes)
6. Conclude – review peer work. (5 minutes)
N.B. Do note that bigger tasks may spread across two lessons.
47 | P a g e
Candidate: 10003313
Tkinter Widgets Table
Widget
Description
Button
A simple button, used to execute a command or other operation.
Canvas
Structured graphics. This widget can be used to draw graphs and plots, create
graphics editors, and to implement custom widgets.
Checkbutton
Represents a variable that can have two distinct values. Clicking the button
toggles between the values.
Entry
A text entry field.
Frame
A container widget. The frame can have a border and a background, and is
used to group other widgets when creating an application or dialog layout.
Label
Displays a text or an image.
Listbox
Displays a list of alternatives. The listbox can be configured to get radiobutton
or checklist behavior.
Menu
A menu pane. Used to implement pulldown and popup menus.
Menubutton
A menubutton. Used to implement pulldown menus.
Message
Display a text. Similar to the label widget, but can automatically wrap text to a
given width or aspect ratio.
Radiobutton
Represents one value of a variable that can have one of many values. Clicking
the button sets the variable to that value, and clears all other radiobuttons
associated with the same variable.
Scale
Allows you to set a numerical value by dragging a "slider".
Scrollbar
Standard scrollbars for use with canvas, entry, listbox, and text widgets.
Text
Formatted text display. Allows you to display and edit text with various styles
and attributes. Also supports embedded images and windows.
Toplevel
A container widget displayed as a separate, top-level window.
Font Style Options
Option
Type
Description
family
string
Font family.
size
integer
Font size in points. To give the size in pixels, use a
negative value.
weight
constant
Font thickness. Use one of NORMAL or BOLD. Default
is NORMAL.
slant
constant
Font slant. Use one of NORMAL or ITALIC. Default
is NORMAL.
underline
flag
Font underlining. If 1 (true), the font is underlined.
Default is 0 (false).
overstrike
flag
Font strikeout. If 1 (true), a line is drawn over text written
with this font. Default is 0 (false).
Source - http://www.pythonware.com/library/tkinter/introduction/x444-fonts.htm (2012)
48 | P a g e
Candidate: 10003313
Tk Option Data Types
anchor
Legal values are points of the compass: "n", "ne", "e", "se", "s", "sw", "w",
"nw", and also "centre".
bitmap
There are eight built-in, named bitmaps: 'error', 'gray25', 'gray50',
'hourglass', 'info', 'questhead', 'question', 'warning'. To specify an X bitmap
filename, give the full path to the file, preceded with an @, as in
"@/usr/contrib/bitmap/gumby.bit".
Boolean
You can pass integers 0 or 1 or the strings "yes" or "no" .
callback
This is any Python function that takes no arguments. For example:
def print_it():
print ("hi there")
fred["command"] = print_it
colour
Colours can be given as the names of X colours in the rgb.txt file, or as
strings representing RGB values in 4 bit: "#RGB", 8 bit: "#RRGGBB", 12 bit”
"#RRRGGGBBB", or 16 bit "#RRRRGGGGBBBB" ranges, where R,G,B here
represent any legal hex digit. See page 160 of Ousterhout’s book for details.
cursor
The standard X cursor names from cursorfont.h can be used, without the
XC_ prefix. For example to get a hand cursor (XC_hand2), use the string
"hand2". You can also specify a bitmap and mask file of your own. See page
179 of Ousterhout’s book.
distance
Screen distances can be specified in either pixels or absolute distances.
Pixels are given as numbers and absolute distances as strings, with the
trailing character denoting units: c for centimetres, i for inches, m for
millimetres, p for printer’s points. For example, 3.5 inches is expressed as
"3.5i".
font
Tk uses a list font name format, such as {courier 10 bold}. Font sizes with
positive numbers are measured in points; sizes with negative numbers are
measured in pixels.
geometry
This is a string of the form widthxheight, where width and height are
measured in pixels for most widgets (in characters for widgets displaying
text). For example: fred["geometry"] = "200x100".
49 | P a g e
Candidate: 10003313
justify
Legal values are the strings: "left", "center", "right", and "fill".
region
This is a string with four space-delimited elements, each of which is a legal
distance (see above). For example: "2 3 4 5" and "3i 2i 4.5i 2i" and "3c 2c 4c
10.43c" are all legal regions.
relief
Determines what the border style of a widget will be. Legal values are:
"raised", "sunken", "flat", "groove", and "ridge".
scroll command
This is almost always the set() method of some scrollbar widget, but can be
any widget method that takes a single argument. Refer to the file
Demo/tkinter/matt/canvas-with-scrollbars.py in the Python source
distribution for an example.
wrap:
Must be one of: "none", "char", or "word".
50 | P a g e
Candidate: 10003313
Lesson 5. PyProcessing an Introduction
PyProcessing is another module which enhances the capabilities of Python, users are allowed to
experience Python differently using a graphical output. This is a more friendly approach to
teaching Python to a younger generation. The main thing for us here is that Pyprocessing runs on
Windows!
Oudkerk (2008) suggests that Pyprocessing is an element of the programming language
Processing to Python. It is best to develop code using a Python IDE (Integrated Development
Environment).
Claudio (2010) has a very useful web-link which gives all information required for Pyprocessing. It
is available at http://code.google.com/p/pyprocessing/wiki/README. The project mission was to
integrate Processing’s friendly graphics into Python, which would be coded using Python code.
To run Pyprocessing, you must download all necessary files, and make sure they are all in the
correct file directories. Pyprocessing currently works most stable on Python 2.x, although as the
code is open source many are trying to overcome this barrier.
Python 3.3 does not support Pyprocessing, so to use this particular module we must download
Python 2.4 – 2.7, I will be using version 2.6; these files can be located at:
http://www.python.org/download/
Follow the same installation process as you did when installing Python 3.x.
The figure above shows the error message on Python 3.3.0 when trying to import ‘Pyprocessing’
51 | P a g e
Candidate: 10003313
Once you have downloaded and installed Python 2.6, download and install Pyprocessing, which
can be located at:
http://code.google.com/p/pyprocessing/downloads/list. Choose the Windows option, and follow
all of the installation steps once again.
Save the Pyprocessing files in the correct directories. For example my copy is saved in
‘C:\Python26\Lib\pyprocessing’ it could also be saved in: ‘C:\Python26\Lib\sitepackages\pyprocessing’
52 | P a g e
Candidate: 10003313
Now that this is done, try importing the PyProcessing module (in Python 2.6.), to see if the
installation went smoothly.
We have successfully imported Pyprocessing!
N.B. If for some reason you get an error message, something will have gone wrong, if it cannot find the
module, make sure it is saved in the root directory of Python.
However if it asks for ‘Pyglet’ like the image below skip this section for now, and come back to it later!
Please go to the ‘Pyglet Package’ section and install it. The Pyglet section starts on page 60
53 | P a g e
Candidate: 10003313
Now let us execute some code to see how it works,
Below is an example of ‘Processing’ code and ‘Python’s interpretation of it.
Example 1: PyProcessing
#
# pyprocessing equivalent
#
from pyprocessing import *
size(200,200)
rectMode(CENTER)
rect(100,100,20,100)
ellipse(100,70,60,60)
ellipse(81,70,16,32)
ellipse(119,70,16,32)
line(90,150,80,160)
line(110,150,120,160)
run()
Source code above is available from: http://code.google.com/p/pyprocessing/
//
// Processing
//
size(200,200);
rectMode(CENTER);
rect(100,100,20,100);
ellipse(100,70,60,60);
ellipse(81,70,16,32);
ellipse(119,70,16,32);
line(90,150,80,160);
line(110,150,120,160);
Copy and paste the Python code onto a ‘New Window’ of Python 2.6 IDLE. Save the code in a
folder named ‘Pyprocessing work’ (remember its location; mine is saved in the Python root
folder.)
The code above was taken from the geniuses at: http://code.google.com/p/pyprocessing/
54 | P a g e
Candidate: 10003313
Example 2: Helloworld.py
Now let’s go back a few steps, and create a ‘Hello World’ program.
This program is a simple text output of the words ‘Hello World’ once created you can play around
and create new text outputs.
Shall we begin!
Type this text into a Python window, and execute it.
Size – sets the dimensions of the canvas that the text will be displayed on.
You can change the text font, alignment, and what the text reads.
Lets try this again and add some animation to the text.
55 | P a g e
Candidate: 10003313
Example 3: Helloworldrot.py
The animation added within the code will enable the text to
rotate.
The background colour of the canvas has been set to ‘Black’ and
the text colour is ‘White’.
Looking closely at the codewe can see just how easy it is to read
and decipher Python code.
Import – brings in a file.
Size – dimension of the canvas
TextFont/Align – simple.
Def = Define
def draw(): - this here tells us what we want the program to
do.
The ‘Hello World’ text is the result of the programmed code.
56 | P a g e
Candidate: 10003313
PyProcessing Questions and Challenges
Now that you have been shown an example, create three different programs.
All of the programs you create should have different text, colours and rotation speeds.
Example:
1.) ‘Hello my name is ________’
2.) ‘Pyprocessing is cool!’
3.) ‘I am always learning’
Below are print screens of programs, to help give you an idea;
More advanced and exceptional pyprocessing features allow you to produce things like:
Many examples of Pyprocessing are available to download from:
http://code.google.com/p/pyprocessing/downloads/list. Choose the ‘examples.zip’, once this is done,
locate the download and put it into your Python program files folder. Mine are located in:
C:\Python26\WORK.
Project
Have a look at the source code (once you have downloaded ‘examples.zip); can you make adapt any of
these files? Can you create a moving object? If you can, try it from scratch!
57 | P a g e
Candidate: 10003313
Pyprocessing in school:
What can it bring to education?
Teachers and educators may feel that the basic Python language may not be at all engaging to their
students. Pyprocessing allows pupils to experience a ‘fun’ graphical output to the basic text and
numerical output of Python’s IDLE. Make sure you take time out yourself to familiarise yourself with
the basic Pyprocessing commands.
As you have been shown (in the previous section), Pyprocessing will allow you to code and create
graphical figures, shapes, sketches, image galleries and much more.
Pyprocessing Tutorial which is available at:
http://code.google.com/p/pyprocessing/wiki/BasicTutorial. This takes you through the following.

The basics

Hello World

Geometric shapes

Colours

Line and border attributes

Continuous applications

Interactions

Images

Transforms
As teachers, you may be able to use Pyprocessing in year 8 – 10 classes. Year 7 pupils should be taught
the basics of programming and be given an introduction to Python (and maybe Pyprocessing). Year 11
students on the other hand should only be approached if they have a desire/ passion to learn Python.
(Many may want to focus on GCSE exams)
All lessons should be well structured and planned; especially a programming lesson. Lessons that are
not well planned may not go as smoothly as intended. The best thing to do would be to follow a plan:
1.) Go through lesson objectives
2.) Give an introduction to the topic (Python/ PyProcessing)
3.) Set a task. (simple to begin with, then maybe a more advanced one for the pupils that can
cope)
4.) Give your students some time getting used to the code and various Syntax.
a. Give them some assistance with the online documentation available.
b. Python - http://www.python.org/
c. Pyprocessing - http://code.google.com/p/pyprocessing/
5.) Round off the lesson with a few challenges, get the pupils into groups (and work on one
machine)
6.) Conclude – review peer work.
58 | P a g e
Candidate: 10003313
Pyprocessing Variables
All of the functions listed below are used to program Pyprocessing, can be found at:
http://code.google.com/p/pyprocessing/wiki/QuickReference
This pack will not be going through all of them, however, you will have been given an introduction to
coding using some of the functions below. It is advised that you take some time out and read the
variables over the next several pages.
More advice on how to code using the various variables can be found at:
http://www.processing.org/reference/
Structure
Processing
PyProcessing Description
draw()
draw()
a function of your program that is called for drawing a frame
exit()
exit()
exits the application
loop()
loop()
makes draw() be called periodically
noLoop()
noLoop()
stops draw() from being called periodically
popStyle() popStyle() restores the prior style settings
pushStyle() pushStyle() saves the current style settings
redraw()
redraw
N/A
run()
your program should call this to map the drawing window and start the
event loop
setup()
setup()
a function of your program that is called automatically once by run()
size()
size()
used to establish the dimensions of the drawing window
Image
Processing
PyProcessing
Description
createImage() createImage() creates an empty PImage object
filter()
screenFilter() applies a filter to the display window
image()
image()
displays a PImage object
imageMode()
imageMode()
changes the semantics of the arguments of image()
loadImage()
loadImage()
loads an image into a PImage object
loadPixels()
loadPixels()
loads the current canvas data into screen pixels
updatePixels() updatePixels() displays the data from screen pixels
59 | P a g e
Candidate: 10003313
get()
get()
returns a copy, a part of a pixel of the screen
set()
setScreen()
sets a position of the screen with data
Environment
Processing
PyProcessing Description
cursor()
cursor()
Changes or shows the mouse cursor.
delay()
delay()
stops the program from running for a specified time
day()
day()
returns the value of the current day
focused
N/A
frameCount frame.count Number of frames drawn so far.
frameRate() frameRate() Sets the number of times draw() will be called per second.
frameRate
frame.rate Estimated number of frames per second for the recent past.
height
height
Height of the drawing window in pixels.
hour()
hour()
returns the value of the current hour
link()
link()
links to a webpage
millis()
millis()
returns the amount of milliseconds since starting a program
minute()
minute()
returns the value of the current minute
month()
month()
returns the value of the current month
noCursor() noCursor() Inhibits the display of the mouse cursor.
online
N/A
screen
screen
holds the width, height and pixels of the display.
second()
second()
returns the value of the current second
year()
year()
returns the value of the current year
width
width
width of the drawing window in pixels
60 | P a g e
Candidate: 10003313
Colour
Setting
Processing
PyProcessing
Description
background() background() clears the drawing with a background colour
colorMode() colorMode() sets up the colour system (RGB or HSB) for specifying colours
fill()
fill()
specifies the colour for drawing filled shapes
noFill()
noFill()
makes shapes be rendered non-filled
noStroke()
noStroke()
makes shapes be rendered without their borders
stroke()
stroke()
specifies the colour for drawing lines and shape borders
noTint()
noTint()
reverts to displaying images with their original values
tint()
tint()
sets the fill value for displaying images
Creating & Reading
Processing
PyProcessing
Description
alpha()
alpha()
returns the alpha (transparency) component of a colour
blendColor() blendColor() returns the blending between two colours
blue()
blue()
returns the blue component of a colour
brightness() brightness() returns the brightness of a colour
color()
color()
builds a colour value from its components
green()
green()
returns the green component of a colour
hue()
hue()
returns the hue of a colour
lerpColor() lerpColor() returns a linear interpolation between two colours
red()
red()
returns the red component of a colour
saturation() saturation() returns the saturation of a colour
61 | P a g e
Candidate: 10003313
Shape
2D Primitives
Processing
PyProcessing Description
arc()
arc()
draws an arc of ellipse
ellipse() ellipse() draws an ellipse
line()
line()
draws a line segment
point()
point()
draws a point
quad()
quad()
draws a quadrilateral
rect()
rect()
draws a rectangle
triangle() triangle() draws a triangle
3D Primitives
Processing
PyProcessing
Description
box()
box()
draws a parallelepiped
sphere()
sphere()
draws a sphere
sphereDetail() sphereDetail() sets the level of detail used to render spheres
Curves
Processing
PyProcessing
Description
bezier()
bezier()
Draws a cubic Bézier curve
bezierDetail()
bezierDetail()
Changes sampling rate of Bézier curves
bezierPoint()
bezierPoint()
Evaluates one coordinate of a point on a Bézier curve
bezierTangent() bezierTangent() Evaluates one coordinate of a tangent of a Bézier curve
curve()
curve()
Draws a cubic Catmull-Rom curve
curveDetail()
curveDetail()
Changes the sampling rate of Catmull-Rom curves
curvePoint()
curvePoint()
Evaluates one coordinate of a point of a Catmull-Rom
curve
curveTangent()
curveTangent()
Evaluates one coordinate of a tangent of a Catmull-Rom
curve
curveTightness() curveTightness() Changes the tightness of Catmull-Rom curves
62 | P a g e
Candidate: 10003313
Attributes
Processing
PyProcessing
Description
noSmooth()
noSmooth()
renders in non-antialiased mode
rectMode()
rectMode()
changes the semantics of the arguments of rect()
ellipseMode() ellipseMode() changes the semantics of the arguments of ellipse()
smooth()
smooth()
strokeCap()
N/A
strokeJoin()
N/A
renders in antialiased mode
strokeWeight() strokeWeight() changes the thickness of lines
Vertex
Processing
PyProcessing
Description
bezierVertex() bezierVertex() adds a Bézier arc to the shape
curveVertex() curveVertex() adds a Catmull-Rom arc to the shape
endShape()
endVertex()
finishes the shape
texture()
texture()
sets a texture to be applied when drawing
textureMode() textureMode() changes how texture coordinates are evalued
vertex()
vertex()
adds a vertex to the shape
Input
Mouse
Processing
PyProcessing
Description
mouseButton
mouse.button
tells what mouse button is pressed.
mouseClicked() mouseClicked() called when a mouse button is pressed and released
mouseDragged() mouseDragged() called when a mouse is dragged with a pressed button
mouseMoved()
63 | P a g e
mouseMoved()
called when a mouse is moved with buttons pressed
Candidate: 10003313
mousePressed() mousePressed() called when a mouse button is pressed
mousePressed
mouse.pressed
tells whether a mouse button is pressed
mouseReleased() mouseReleased() called when a mouse button is released
mouseX
mouse.x
current x position of the mouse
mouseY
mouse.y
current y position of the mouse
pmouseX
pmouse.x
previous x position of the mouse
pmouseY
pmouse.y
previous y position of the mouse
Keyboard
Processing
PyProcessing
Description
key
key.char
holds the char value of the most recently pressed key
keyCode
key.code
holds an int code of the most recently pressed key
keyPressed() keyPressed() called when a key is pressed
keyPressed
key.pressed() tells whether a key is pressed
keyReleased() keyReleased() called when a key is released
keyTyped()
keyTyped()
called when a non-code key is pressed
Processing
PyProcessing
Description
textAlign()
textAlign()
changes the text alignment attributes
Text
createFont() createFont() creates a font
textFont()
textFont()
sets the received font as current font
htmlText()
htmlText()
draws the html text at the given position
text()
text()
draws the text at the given position
textSize()
textSize()
changes the current font size
textWidth()
textWidth()
returns the width of the received string rendered in the current
font
textAscent() textAscent() returns the ascent of the current font
textDescent() textDescent() returns the descent of the current font
64 | P a g e
Candidate: 10003313
Math
Processing
PyProcessing
Description
PVector
PVector
a class used to describe two or three dimensional vectors
noise()
noise()
returns the perlin noise value at specified coordinates
binary()
binary()
converts a value to a string in binary notation
hex()
hex()
converts a value to a string in hexadecimal notation
unbinary() unbinary() converts a string in binary notation to its decimal value
unhex()
unhex()
converts a string in hexadecimal notation to its decimal value
byte()
byte()
converts a char or int to its byte representation
constrain() constrain() returns the constrained value according to the received parameters
dist()
dist()
returns the Euclidean distance between two points
map()
map()
re-maps a number from one range to another
mag()
mag()
returns the magnitude of a vector
lerp()
lerp()
returns a interpolation between two numbers
sq()
sq()
returns the square of a value
Transform
Processing
PyProcessing
Description
applyMatrix() applyMatrix() multiplies the current transformation matrix by a given matrix
getMatrix()
getMatrix()
popMatrix()
popMatrix()
returns the MODELVIEW matrix
discards the current (top) matrix from the
transformation matrix stack
printMatrix() printMatrix() prints the current transformation matrix
pushMatrix() pushMatrix()
65 | P a g e
pushes a copy of the current matrix onto the transformation
matrix stack
Candidate: 10003313
resetMatrix() resetMatrix() sets an identity matrix as the the current transformation matrix
rotate()
rotate()
rotates around a given axis
rotateX()
rotateX()
rotates around the x axis
rotateY()
rotateY()
rotates around the y axis
rotateZ()
rotateZ()
rotates around the z axis
shearX()
shearX()
shears a shape around the x axis
shearY()
shearY()
shears a shape around the y axis
scale()
scale()
performs a scale transformation
translate()
translate()
performs a translation transformation
Lights, Camera
Lights
Processing
PyProcessing
Description
ambientLight()
ambientLight()
adds an ambient light source
directionalLight() directionalLight adds a directional light source
lightFalloff()
lightFalloff()
lightSpecular()
lightSpecular() sets specular coefficients for next light sources
lights()
lights()
turns on lighting and default light sources
noLights()
noLights()
turns off lighting
normal()
normal()
sets the normal vector for subsequent vertices
pointLight()
pointLight()
adds a point light source
spotLight()
spotLight()
adds a spot light source
66 | P a g e
sets attenuation factors for next light sources
Candidate: 10003313
Camera
Processing
PyProcessing
Description
beginCamera()
N/A
camera()
camera()
endCamera()
N/A
ortho()
ortho()
sets an orthogonal projection
perspective()
perspective()
sets a perspective projection
printCamera()
printCamera()
prints the current transformation matrix
getProjection()
getProjection()
returns the PROJECTION matrix
sets the camera transformation
printProjection() printProjection() prints the current projection matrix
Coordinates
Processing
PyProcessing
Description
modelX() modelX()
returns the screen x coordinate of given object coordinates
modelY() modelY()
returns the screen y coordinate of given object coordinates
modelZ() modelZ()
returns the screen z coordinate of given object coordinates
N/A
modelXYZ() returns the screen coordinates of given object coordinates
screenX() screenX()
returns the screen x coordinate of given object coordinates
screenY() screenY()
returns the screen y coordinate of given object coordinates
screenZ() screenY()
returns the screen z coordinate of given object coordinates
N/A
screenXYZ() returns the screen coordinates of given object coordinates
Material Properties
Processing
PyProcessing
Description
ambient()
ambient()
sets the ambient properties of the next vertices
emissive() emissive() sets the emissive properties of the next vertices
shininess() shininess() sets the shininess property of the next vertices
specular() specular() sets the specular properties of the next vertices
67 | P a g e
Candidate: 10003313
Pyglet Package – Extension task
If you are asked, by IDLE to have Pyglet installed onto your machine when importing ‘Pyprocessing’ go
to, www.pyglet.org/download.html. From here you will be given a list of options. We will be choosing
‘pyglet – 1.1.4.msi: Windows Installer, includes Avbin-5’ this version is for Windows.
Click on run.
The installation process chooses the root destination of the files (most likely within the Python folder). In order
to use Pyprocessing you may need to install Pyglet.
68 | P a g e
Candidate: 10003313
Now that Pyglet has been successfully installed there should be no error messages when attempting to
import the files.
Now that this is done, and that it imports correctly, go back to the ‘Pyglet’ website. To find some
examples of what Pyglet is used for, click on the link shown below, open or save it (I would save it
within my Python 2.6 folder)
N.B. It is in the Source Distributions section.
Locate the folder (unzip it, so you have access to the files) open up the folder (mine is located in the
root folder of Python 2.6 (or equivalent for Pyprocessing) and have a look at the ‘Pyglet installed
folder, and its ‘examples’, (for example my folder is saved in: C:\Python26\pyglet-1.1.4.).
69 | P a g e
Candidate: 10003313
If you require more assistance with using Pyglet, documentation is also available within the
installation. Inside the Pyglet-1.1.4 folder click on ‘doc’ then ‘html’ – for a web based view, or ‘pdf’ for
a text based view. Mine is located in: F:\Python26\pyglet-1.1.4\doc\pdf.
Some of the examples of Pyglet are fascinating, just to think Python (and its subsidiary modules)
enable us to create such brilliant programs, both simple and advances





Simple text
Image
Games
Multi-media
HTML
Examples of which can be found in the ‘pyglet-1.1.4’ folder. Below are some program examples.
(source on page 69)
Project
Have a look at the source code of some of the programs above; can you make/adapt any of these
files?
70 | P a g e
Candidate: 10003313
Lesson 5: Python Challenges Questions
This section provides you with some Python challenges, whereby you can attempt to code various
programs. Remember to check sources online for help, it is not cheating!
As you code your program, it is advised that you keep documentation of the development stages; this
is for your benefit, as you can then learn from your own code.
N.B. Answers can be found after this section – please try to answer the questions before looking at the
answers.
1.) Code a star using logo in Python (8 sided star)
2.) When programming a game of ping pong, what are the main classes (components) needed?
3.) Code a small simple shape (using Python 2.x – via the graphics module)
4.) Create a program whereby a user can interact with it. Maybe a moving image, or a static
program where a simple ’click of the mouse’ can change the position or colour of an image?
o Refer back to lesson 3 – “Understanding a created Library”
o Example code in answers section – source Price (2012)
o Note for this question you may need to use Python 2.x
5.) Create a simple calculation program – convert Celsius to Fahrenheit.
a. You will need to know how to work out the difference between both.
6.) Go back to the PyProcessing section and try to create another ‘odd’ looking character like the
one in ‘Example 1’ however alter the size, and maybe colour of the objects.
71 | P a g e
Candidate: 10003313
Python Challenges Answers
1.)
import turtle
t = turtle.Pen()
for x in range(1,9):
t.forward(100)
t.left(225)
2.) Classes: Ball, Paddle, Wall
3.) [
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # pause for click in window
win.close()
main()
]
4.) 1. [
from graphics import *
def main()
win = GraphWin("My Circle",500,500)
c = Circle(Point(200,200),100)
c.setFill('red')
c.setOutline('green')
c.setWidth(10)
c.draw(win)
r = Rectangle(Point(300,300),Point(400,400))
r.setFill('orange')
r.setOutline('cyan')
r.setWidth(10)
72 | P a g e
Candidate: 10003313
r.draw(win)
# Now let's try to output some text
text = Text(Point(250,250), 'Hello');
text.setSize(20);
text.draw(win)
# now infinite loop to move a shape
while 1 == 1:
# wait until the mouse is clicked. Why can't we drag?
mouseLocn = win.checkMouse()
while mouseLocn == None :
mouseLocn = win.checkMouse()
circlLocn = c.getCenter()
c.move(mouseLocn.getX()-circlLocn.getX(),0)
# convert a number to a string
# display two elements into a string, the x and y components
of a mouse position
text.setText(str(mouseLocn.getX()) + '\n' +
str(mouseLocn.getY()) )
# waits for mouse click to close window
win.getMouse()
win.close()
main()
]
73 | P a g e
Candidate: 10003313
2. [
# CBP 24-10-12
# First explorations into Python (ctd)
# Includes new library CBPLib1 using Zwelle's to replicate Processing.
# Experimenting with movement (a la Processing)
# Wait function ivoking Python's sleep() to step an objec throug space.
# Mmm not happy about this.
from CBPLib1 import *
from graphics import *
def main():
# Let's draw a circle
fill(255,255,0)
stroke(0,255,255)
strokeWeight(4)
myCircle(100,100,50)
# Now let's move the circle to the right
x = 100
while x < 350:
x = x + 20
wait(1)
myCircle(10+x,10+x,10)
# check for a mouse click to interrupt (still Zelle)
# really must fix this
if win.checkMouse() != None:
win.close()
74 | P a g e
Candidate: 10003313
# Not happy about this. Could be instatiating multiple objects and
# relying on the garbage collector to help us out. Bad language :(
# must try in the next period to get the .move() fn working.
# waits for mouse click to close window.
# use Zelle for the mo. This may need some thought
win.getMouse()
win.close()
main()
]
5.) Celsius to Fahrenheit
[
def C2F():
Celsius
= input ('Enter degrees in Celsius: ');
Fahrenheit = (9.0/5.0) * Celsius +32;
print Celsius, 'Celsius =', Fahrenheit, 'Fahrenheit';
]
7.) Sleep program
[
from time import sleep
print("We'll start off by sleeping 5 seconds")
# make the program sleep for 5 seconds
sleep(5)
print("Ok, time to wake up!")
wait_time = int(input("How much longer would you like to sleep? "))
while wait_time > 0:
print("Ok, we'll sleep for " + str(wait_time) + " more
seconds...")
sleep(wait_time)
wait_time = int( input( "How much longer would you like to
sleep? "))
print( "We're done!" )
]
75 | P a g e
Candidate: 10003313
Appendix
Debugging
1.
[
# epdb1.py -- experiment with the Python debugger, pdb
a = "aaa"
b = "bbb"
c = "ccc"
final = a + b + c
print final
]
2. Insert – import pdb
3. insert (where you would like your tracing to begin) pdb.set_trace()
4. your program now looks like;
[
# epdb1.py -- experiment with the Python debugger, pdb
import pdb
a = "aaa"
pdb.set_trace()
b = "bbb"
c = "ccc"
final = a + b + c
print final
]
Python Basics - Maths
[
>>> for n in range (1, 10):
print (n**2)
]
Python -
Example 1: Numerical Input.py
[
print()
print( "Welcome to the Area calculation program" )
print( "---------------------------------------" )
print()
# Print out the menu:
print( "Please select a shape:" )
print( "1 Rectangle" )
76 | P a g e
Candidate: 10003313
print( "2
print()
Circle" )
# The input function both prompts the user for input and fetches
it...
shape = int( input( "> " ) )
# Calculate the area...
if shape == 1:
height = int( input("Please enter the height: ") )
width = int( input("Please enter the width: ") )
area = height*width
print( "The area is", area )
else:
radius = int( input("Please enter the radius: ") )
area = 3.14*(radius**2)
print( "The area is", area )
input( '\n\nPress Enter to exit...' )
]
Example 2: GuessTheNumberBySaagarJagatia.py
[
import random
num = random.randint(1, 100)
while True:
print('Guess a number between 1 and 100')
guess = input()
i = int(guess)
if i == num:
print('You guessed right')
break
elif i < num:
print('Try higher')
elif i > num:
print('Try lower')
]
77 | P a g e
Candidate: 10003313
Example 3: HangmanBySaagarJagatia.py
[
import random
mistakes = int(0)
print("The Hangman Game Guess The Word!")
print("But Be Quick You Only Have 7 Mistakes!!")
print("The Words Are Based On Python Programming")
potentional_words = ["print", "import", "python", "rossum",
"idle", "shell"] #all the words that the computer can chose from
word = random.choice(potentional_words)
letters = list(word)
print("") #making it look nice
if word == "print":
blankedword = str("________")
print("The Word Has 5 Letters In It. Guess
elif word == "import":
blankedword = str("________")
print("The Word Has 6 Letters In It. Guess
elif word == "python":
blankedword = str("________")
print("The Word Has 6 Letters In It. Guess
the user how many letter they need to guess
elif word == "rossum":
blankedword = str("________")
print("The Word Has 6 Letters In It. Guess
elif word == "idle":
blankedword = str("________")
print("The Word Has 4 Letters In It. Guess
elif word == "shell":
blankedword = str("________")
print("The Word Has 5 Letters In It. Guess
What It Is")
What It Is")
What It Is") #tells
What It Is")
What It Is")
What It Is")
print("")
guessedletters = list(blankedword)
while(mistakes != 7):
stops
#if they make 5 mistakes then the loop
if guessedletters == letters:
print("")
print("Welldone You Have Guessed The Word! You WIN!") #if
they guess all the letters then they win
input("")
break
guess = str(input("What is your guess? "))
if word == "print":
if guess == "p":
guessedletters[0] = "p"
print(str(guessedletters))
elif guess == letters[1]:
guessedletters[1] = "r"
78 | P a g e
Candidate: 10003313
print(str(guessedletters))
elif guess == letters[2]:
guessedletters[2] = "i"
print(str(guessedletters))
elif guess == letters[3]:
guessedletters[3] = "n"
print(str(guessedletters))
elif guess == letters[4]:
guessedletters[4] = "t"
print(str(guessedletters))
print("Welldone You Have Guessed The Word! You WIN!")
#if they guess the words then they win
input ("")
break
else:
mistakes = mistakes + 1
print("")
print("WRONG! Adding 1 To Your Mistakes...")
they make a mistake then it adds one to their mistakes
print("You've Made", mistakes, "Mistakes")
print("")
#if
if word == "import":
if guess == "i":
guessedletters[0] = "i"
print(str(guessedletters))
elif guess == letters[1]:
guessedletters[1] = "m"
print(str(guessedletters))
elif guess == letters[2]:
guessedletters[2] = "p"
print(str(guessedletters))
elif guess == letters[3]:
guessedletters[3] = "o"
print(str(guessedletters))
elif guess == letters[4]:
guessedletters[4] = "r"
print(str(guessedletters))
elif guess == letters[5]:
guessedletters[5] = "t"
print(str(guessedletters))
elif guess == word:
print("Welldone You Have Guessed The Word! You WIN!")
input("")
break
else:
mistakes = mistakes + 1
print("")
print("WRONG! Adding 1 To Your Mistakes...")
79 | P a g e
Candidate: 10003313
print("You've Made", mistakes, "Mistakes")
print("")
if word == "python":
if guess == "p":
guessedletters[0] = "p"
print(str(guessedletters))
elif guess == letters[1]:
guessedletters[1] = "y"
print(str(guessedletters))
elif guess == letters[2]:
guessedletters[2] = "t"
print(str(guessedletters))
elif guess == letters[3]:
guessedletters[3] = "h"
print(str(guessedletters))
elif guess == letters[4]:
guessedletters[4] = "o"
print(str(guessedletters))
elif guess == letters[5]:
guessedletters[5] = "n"
print(str(guessedletters))
elif guess == word:
print("Welldone You Have Guessed The Word! You WIN!")
input("")
break
else:
mistakes = mistakes + 1
print("")
print("WRONG! Adding 1 To Your Mistakes...")
print("You've Made", mistakes, "Mistakes")
print("")
if word == "rossum":
if guess == letters[0]:
guessedletters[0] = "r"
print(str(guessedletters))
elif guess == letters[1]:
guessedletters[1] = "o"
print(str(guessedletters))
elif guess == letters[2]:
guessedletters[2] = "s"
guessedletters[3] = "s"
print(str(guessedletters)) #if they guess a letter
that is in the word then it adds it splice the letter(s) into the
guessed letters
elif guess == letters[4]:
guessedletters[4] = "u"
print(str(guessedletters))
elif guess == letters[5]:
guessedletters[5] = "m"
print(str(guessedletters))
80 | P a g e
Candidate: 10003313
print("Welldone You Have Guessed The word! You WIN!")
#if they guess the word then they win
input("")
break
else:
mistakes = mistakes + 1
print("")
print("WRONG! Adding 1 To Your Mistakes...")
they make a mistake then it adds one to their mistakes
print("You've Made", mistakes, "Mistakes")
print("")
#if
if word == "idle":
if guess == "i":
guessedletters[0] = "i"
print(str(guessedletters))
elif guess == letters[1]:
guessedletters[1] = "d"
print(str(guessedletters))
elif guess == letters[2]:
guessedletters[2] = "l"
print(str(guessedletters))
elif guess == letters[3]:
guessedletters[3] = "e"
print(str(guessedletters))
elif guess == word:
print("Welldone You Have Guessed The Word! You WIN!")
input("")
break
else:
mistakes = mistakes + 1
print("")
print("WRONG! Adding 1 To Your Mistakes...")
print("You've Made", mistakes, "Mistakes")
print("")
if word == "shell":
if guess == "s":
guessedletters[0] = "s"
print(str(guessedletters))
elif guess == letters[1]:
guessedletters[1] = "h"
print(str(guessedletters))
elif guess == letters[2]:
guessedletters[2] = "e"
print(str(guessedletters))
elif guess == letters[3]:
guessedletters[3] = "l"
guessedletters[4] = "l"
print(str(guessedletters))
elif guess == word:
print("Welldone You Have Guessed The Word! You WIN!")
81 | P a g e
Candidate: 10003313
input("")
break
else:
mistakes = mistakes + 1
print("")
print("WRONG! Adding 1 To Your Mistakes...")
print("You've Made", mistakes, "Mistakes")
print("")
if mistakes == 7:
print("You've Made Too Many Mistakes The", word, "Was Not
Guessed, Better Luck Next Time")
#if they have made 7 mistakes
it tell them what the word was
input("")
]
Tkinter -
Example 1:HelloWorld.py
[
from tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
]
82 | P a g e
Candidate: 10003313
Example 2: SimpleCalculator.py
[
from tkinter import *
def frame(root, side):
w = Frame(root)
w.pack(side=side, expand=YES, fill=BOTH)
return w
def button(root, side, text, command=None):
w = Button(root, text=text, command=command)
w.pack(side=side, expand=YES, fill=BOTH)
return w
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('Simple Calculator')
self.master.iconname("calc1")
display = StringVar()
Entry(self, relief=SUNKEN,
textvariable=display).pack(side=TOP, expand=YES,
fill=BOTH)
for key in ("123", "456", "789", "-0."):
keyF = frame(self, TOP)
for char in key:
button(keyF, LEFT, char,
lambda w=display, s=' %s '%char: w.set(w.get()+s))
opsF = frame(self, TOP)
for char in "+-*/=":
if char == '=':
btn = button(opsF, LEFT, char)
btn.bind('<ButtonRelease-1>',
lambda e, s=self, w=display: s.calc(w), '+')
83 | P a g e
Candidate: 10003313
else:
btn = button(opsF, LEFT, char,
lambda w=display, c=char: w.set(w.get()+' '+c+' '))
clearF = frame(self, BOTTOM)
button(clearF, LEFT, 'Clr', lambda w=display: w.set(''))
def calc(self, display):
try:
display.set(eval(display.get()))
except ValueError:
display.set("ERROR")
if __name__ == '__main__':
Calculator().mainloop()
]
PyProcessing -
Example 1:PyProcessing.py
[
#
# pyprocessing equivalent
#
from pyprocessing import
size (200, 200)
rectMode(CENTER)
rect(100,100,20,100)
ellipse(100,70,60,60)
ellipse(81,70,16,32)
ellipse(119,70,16,32)
line(90,150,80,160)
line(110,150,120,160)
run()
]
84 | P a g e
Candidate: 10003313
Example 2:HelloWorld.py
[
from pyprocessing import *
size(300,300,caption="Hello")
textFont(createFont("Times", 36, bold=True, italic=True))
textAlign(CENTER)
text("Hello world", width/2, height/2)
run()
]
Example 3: HelloWorldRot.py
[
from pyprocessing import *
size(300,300)
textFont(createFont("Times New Roman", 36))
textAlign(CENTER,CENTER)
ang = 0
def draw():
global ang
background(0,0,0)
fill (255)
translate (width/2, height/2)
rotateZ (ang)
ang += 0.01
text("Hello world", 0, 0)
run()
]
85 | P a g e
Candidate: 10003313
Something fun for class
1 player pong
[
from tkinter import *
import random
import time
class Ball:
def __init__(self, canvas, paddle, color):
self.canvas = canvas
self.paddle = paddle
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
starts = [-3, -2, -1, 1, 2, 3]
random.shuffle(starts)
self.x = starts[0]
self.y = -3
self.canvas_width = self.canvas.winfo_width()
self.canvas_height = self.canvas.winfo_height()
self.hit_bottom = False
def hit_paddle(self, pos):
paddle_pos = self.canvas.coords(self.paddle.id)
if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
return True
return False
def draw(self):
self.canvas.move(self.id, self.x, self.y)
86 | P a g e
Candidate: 10003313
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.y = 3
if self.hit_paddle(pos) == True:
self.y = -3
if pos[3] >= self.canvas_height:
self.hit_bottom = True
if pos[0] <= 0:
self.x = 3
if pos[2] >= self.canvas_width:
self.x = -3
class Paddle:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
self.canvas.move(self.id, 200, 300)
self.x = 0
self.canvas_width = self.canvas.winfo_width()
self.started = False
self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
self.canvas.bind_all('<Button-1>', self.start_game)
def draw(self):
self.canvas.move(self.id, self.x, 0)
pos = self.canvas.coords(self.id)
if pos[0] <= 0:
self.x = 0
elif pos[2] >= self.canvas_width:
87 | P a g e
Candidate: 10003313
self.x = 0
def turn_left(self, evt):
self.x = -2
def turn_right(self, evt):
self.x = 2
def start_game(self, evt):
self.started = True
tk = Tk()
tk.title("Game")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update()
paddle = Paddle(canvas, 'black')
ball = Ball(canvas, paddle, 'red')
while 1:
if ball.hit_bottom == False and paddle.started == True:
ball.draw()
paddle.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
88 | P a g e
Candidate: 10003313
] Source: Briggs (2012)
References
Abelson. H, (2012) Logo Foundation: What is Logo? [Online] Available from:
http://el.media.mit.edu/logo-foundation/index.html, [Accessed on: 16/12/2012]
Briggs. J, (2012) Python for Kids: A playful introduction. San Francisco. No Starch Press.
Claudio (2010) PyProcessing. [Online] Available from:
http://code.google.com/p/pyprocessing/wiki/README. [Accessed on: 15/01/2013]
Dayley. B, (2006) Understanding Python: Python Objects, Modules, Classes and Functions, In: Python
Phrasebook: Essential Code and Commands. UK. Sams
Doty. S, (2008) Python Basics. [Online] Available from:
http://anh.cs.luc.edu/331/notes/PythonBasics.pdf. [Accessed on: 15/01/2013]
Downey. A, (2012) Think Python: How to Think Like a Computer Scientist. Massachusetts, Green Tea
Press.
Fangohr. H, (2012) Introduction to Python for Computational Science and Engineering: A Beginners
Guide. University of Southampton [Online]. Available at:
http://www.southampton.ac.uk/~fangohr/training/python/pdfs/Python-for-Computational-Scienceand-Engineering.pdf. [Accessed on: 22/11/2012]
Feurzeig. W, Papert. S, Lawler. B, (2011) Programming-Languages as a Conceptual Framework for
Teaching Mathematics. Interactive Learning Environments. 19 (5) 487-501.
GNU. (2007) GUN Lesser General Public License. [Online] Available from:
http://www.gnu.org/licenses/lgpl.txt. [Accessed on: 23/02/2013]
Goldberg. M, (1991) Portrait of Seymour Papert. Educational Leadership. 48 (7) 68-70.
Google Project Housing. (2012) A Processing Like Environment for Doing Graphics with Python.
[Online] Available from: http://code.google.com/p/pyprocessing/. [Accessed on: 23/01/2013]
Grayson. J (2000) Python and Tkinter Programming. Greenwich Manning Publications.
Lodha. S, Somyalipi. S, (2013) Why Computer Science Matters: Introducing Computer Science using
Scratch and Touch Develop. Computer and Information Science Education.
Lungdh. F, (1999) An Introduction to Tkinter. [Online] Available from:
http://www.pythonware.com/library/tkinter/introduction/index.htm. [Accessed on: 21/01/2013]
Maruch. A, Maruch. S, (2006) Python for Dummies, UK, John Wiley & Sons, pp. 36-65
Massachusetts Institute of Technology (2012), Seymour Papert. [Online] Available from:
http://web.media.mit.edu/~papert/. [Accessed on: 16/12/2012]
89 | P a g e
Candidate: 10003313
Mertz. D, (2000) Charming Python: TK Programming in Python. [Online] Available from:
http://www.ibm.com/developerworks/library/l-tkprg/. [Accessed on: 18/01/2013]
Oudkerk. R, (2008) Addition of the Multi-prcessing package to the Standard Library. [Online] Available
from: http://pyprocessing.berlios.de/. [Accessed on: 15/01/2013]
Pitrou. A, (2012). A Finger-Grained Import Lock. [Online] Available from:
http://docs.python.org/3/whatsnew/3.3.html [Accessed on: 21/11/2012]
Price. C (2012) Creative Computing: Learning to Code in Processing for KS3.COMP3007. Dissertation
topic. 1st October. University of Worcester.
PyProcessing. (2012) PyProcessing: A Processing-Like environment for doing graphics with Python.
[Online] Available from: http://code.google.com/p/pyprocessing/. [Accessed on:22/11/2012]
Rossum. G, (2012), Python Tutorial, [Online] Available from: http://docs.python.org. [Accessed on:
29/10/2012]
Rossum. G, (2012) Python Library Reference Manual, [Online] Available from: http://docs.python.org.
[Accessed on: 29/10/2012]
Rossum. G, (2012) Python Library Reference: Release 2.5 [Online] Available from: http://wwwmdp.eng.cam.ac.uk/web/CD/engapps/programming/python/lib.pdf. [Accessed on: 21/11/2012]
Shipman. J, (2013) Tkinter 8.5 Reference: a GUI for Python. [Online] Available from:
http://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf. [Accessed on: 26/02/2013]
Tkinter. (2013) Tkinter [Online] Available from: http://wiki.python.org/moin/TkInter. [Accessed on:
25/02/2013]
90 | P a g e
Candidate: 10003313
Download