My Project Mission
Learning to Program Essential skills to code in Python for KS3 & KS4 -76643313690Saagar JagatiaRelease 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.Table of Contents TOC \o "1-3" \h \z \u Learning to Program PAGEREF _Toc349732369 \h 1Release Information and Copyright Notice PAGEREF _Toc349732370 \h 2Table of Contents PAGEREF _Toc349732371 \h 3Forward PAGEREF _Toc349732372 \h 6Preface PAGEREF _Toc349732373 \h 7My Project Mission PAGEREF _Toc349732374 \h 9Acknowledgements PAGEREF _Toc349732374 \h 9Intro 1a. How To Use This Book PAGEREF _Toc349732375 \h 10Working through the sections PAGEREF _Toc349732376 \h 10Code Examples PAGEREF _Toc349732377 \h 10Intro 1b. Programming in School PAGEREF _Toc349732378 \h 11Logo PAGEREF _Toc349732379 \h 11Scratch PAGEREF _Toc349732381 \h 13Intro 2. Learning and Teaching how to Program PAGEREF _Toc349732382 \h 14Modification (Modding) PAGEREF _Toc349732383 \h 14Extension PAGEREF _Toc349732384 \h 14Collage PAGEREF _Toc349732385 \h 14Reading Code PAGEREF _Toc349732386 \h 15Coding from Scratch PAGEREF _Toc349732387 \h 15Intro 3a. Introduction to Software Development PAGEREF _Toc349732388 \h 16Iterative Development PAGEREF _Toc349732389 \h 16Professional Iterative Software Development PAGEREF _Toc349732390 \h 16Debugging PAGEREF _Toc349732391 \h 16Intro 3b. Strategies for Debugging in Python PAGEREF _Toc349732392 \h 17Syntax Errors PAGEREF _Toc349732393 \h 17Debugging Example PAGEREF _Toc349732394 \h 18Intro 4. Introduction To The Python Language PAGEREF _Toc349732395 \h 19Downloading, Installing, Configuring and Running Python PAGEREF _Toc349732396 \h 19Let’s begin. PAGEREF _Toc349732397 \h 22Official Python Cheat Sheet – for a real head start with the language PAGEREF _Toc349732398 \h 23Now some Python Basics PAGEREF _Toc349732399 \h 24TECHNICAL STUFF: PAGEREF _Toc349732400 \h 25Some Rules and Information PAGEREF _Toc349732401 \h 27Naming Rules PAGEREF _Toc349732402 \h 27Python Data Types PAGEREF _Toc349732403 \h 27Modules PAGEREF _Toc349732404 \h 28Comparing Strings PAGEREF _Toc349732405 \h 29TECHNICAL STUFF: PAGEREF _Toc349732406 \h 29The Three Ds PAGEREF _Toc349732407 \h 29Lesson 1. Lets Dive Into The Code PAGEREF _Toc349732408 \h 30Example 1: Numerical Input.py PAGEREF _Toc349732409 \h 30Example 2: GuessTheNumberBySaagarJagatia.py PAGEREF _Toc349732410 \h 32Example 3: HangmanBySaagarJagatia.py PAGEREF _Toc349732411 \h 33Lesson 2. Understanding the Python Library: ‘Import’ & Creating Modules PAGEREF _Toc349732412 \h 39Using & importing Modules PAGEREF _Toc349732413 \h 39Creating Modules PAGEREF _Toc349732414 \h 40Lesson 3. Understanding a Created Library PAGEREF _Toc349732415 \h 41Graphical Outputs PAGEREF _Toc349732416 \h 41Lesson 4. Tkinter an Introduction PAGEREF _Toc349732417 \h 43Here is a Complete Example PAGEREF _Toc349732418 \h 44Features of Tkinter PAGEREF _Toc349732419 \h 44Example 1: Helloworld.py PAGEREF _Toc349732420 \h 45Example 2: SimpleCalculator.py PAGEREF _Toc349732421 \h 46Tkinter in school: PAGEREF _Toc349732422 \h 47Tkinter Widgets Table PAGEREF _Toc349732423 \h 48Font Style Options PAGEREF _Toc349732424 \h 48Tk Option Data Types PAGEREF _Toc349732425 \h 49Lesson 5. PyProcessing an Introduction PAGEREF _Toc349732426 \h 51Example 1: PyProcessing PAGEREF _Toc349732427 \h 54Example 2: Helloworld.py PAGEREF _Toc349732428 \h 55Example 3: Helloworldrot.py PAGEREF _Toc349732429 \h 56PyProcessing Questions and Challenges PAGEREF _Toc349732430 \h 57Pyprocessing in school: PAGEREF _Toc349732431 \h 58Pyprocessing Variables PAGEREF _Toc349732432 \h 59Structure PAGEREF _Toc349732433 \h 59Image PAGEREF _Toc349732434 \h 59Environment PAGEREF _Toc349732435 \h 60Colour PAGEREF _Toc349732436 \h 61Shape PAGEREF _Toc349732437 \h 62Input PAGEREF _Toc349732438 \h 63Math PAGEREF _Toc349732439 \h 65Transform PAGEREF _Toc349732440 \h 65Lights, Camera PAGEREF _Toc349732441 \h 66Camera PAGEREF _Toc349732442 \h 67Pyglet Package – Extension task PAGEREF _Toc349732443 \h 68Lesson 5: Python Challenges Questions PAGEREF _Toc349732445 \h 71Python Challenges Answers PAGEREF _Toc349732446 \h 72Appendix – Code Snippets PAGEREF _Toc349732447 \h 76Debugging PAGEREF _Toc349732448 \h 76Python Basics - Maths PAGEREF _Toc349732449 \h 76Python - Example 1: Numerical Input.py PAGEREF _Toc349732450 \h 76Example 2: GuessTheNumberBySaagarJagatia.py PAGEREF _Toc349732451 \h 77Example 3: HangmanBySaagarJagatia.py PAGEREF _Toc349732452 \h 78Tkinter - Example 1:HelloWorld.py PAGEREF _Toc349732453 \h 82Example 2: SimpleCalculator.py PAGEREF _Toc349732454 \h 83PyProcessing - Example 1:PyProcessing.py PAGEREF _Toc349732455 \h 84Example 2:HelloWorld.py PAGEREF _Toc349732456 \h 85Example 3: HelloWorldRot.py PAGEREF _Toc349732457 \h 85Something fun for class PAGEREF _Toc349732458 \h 861 player pong PAGEREF _Toc349732459 \h 86References PAGEREF _Toc349732460 \h 89ForwardThis 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)PrefaceThis 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 programmingYou are intelligent and motivated, and have great experience and knowledge with computersYou 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 capabilitiesStudent Assumptions:You have never programmed before, or have had minimal exposure to programmingYou have a personal drive to do wellYou are intelligent and motivated, and have experience and knowledge of using and understanding computersYou 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 moreI, 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 studentsThe 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.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 ClassesInheritancePolymorphism 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 . The primary author of Python is: Guido van Rossum;E-mail: guido@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.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”AcknowledgementsWriting 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.Intro 1a. How To Use This BookWorking through the sectionsThis 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 introductionSome sample code (Print screens, copy and paste version will be available in the appendix)ProjectRandom questions for further developmentSeveral sources may be used to back up information that is stated.Including web links whereby you can enhance your studiesCode 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).Intro 1b. Programming in SchoolCurrently 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:An introduction to what will be taught and learnt. (Lesson Objectives)A run through of the softwareA simple introductory task sheet, which had basic commands.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: 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. "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- importing the module>>> t = turtle.pen()- 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] ProjectTry to create a square, and then move onto creating a more exotic shape. – try a starScratchAvailable at: . 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 gamesWrite interactive stories which also use animationScratch 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)Intro 2. Learning and Teaching how to ProgramYour 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.ExtensionHere, 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.CollageCollage 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.Reading CodeHere, 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 ScratchMost 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.Intro 3a. Introduction to Software DevelopmentOnce 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 DevelopmentHere 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.DebuggingWhen 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. Intro 3b. Strategies for Debugging in PythonWhen 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 ErrorsYour students will probably make some of these common errors.Incorrect CodeErrorCorrect CodePython VersionPRINT “hello world”SyntaxError: invalid syntaxprint “hello world”2.xprint "hello World"SyntaxError: invalid syntaxprint("Hello World")3.xstr( input("What is your guess? ")SyntaxError: invalid syntaxstr(input("What is your guess? "))3.x23-48'SyntaxError: EOL while scanning string literal23-482.x3.xPython 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).Please visit ‘Intro 4’ to view details on how to download and install Python.Debugging ExampleLets create a simple program, in which you can set pdb to trace your code; Now executeAs 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 - 3 adapted from Source: Price (2012)Intro 4. Introduction To The Python LanguageThis 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: it is freely available to download at the following link 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. 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\idlelibOr 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’.ProjectWhy do you think Python and IDLE are named as they are? Why not try to find out...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 from. 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.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.ProjectNow you try to create a few strings of code. – remember to refer back to the examples.-132025408360-1638304781577Official Python Cheat Sheet – for a real head start with the language Now some Python BasicsIt 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 (+): Additionless than (<)Parentheses (()): Groupinggreater than (>)Asterisk (*): Multiplicationequal to (==)Forward Slash (/): Divisionnot equal to (!= or <>)Double asterisk (**): Exponentiation (x to the power of y)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.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] 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 InformationNaming RulesYou 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 aboveBy 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 TypesNumbers – data you would use to do math with.Class - are useful because they can combine both data and methods that operate on that dataModules – is a text file that can contain any kind of Python codeStrings – 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.ModulesA 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 mathOnce the module is imported you can utilize the information within it.Example; to work out what pi is:>>>math.pi3.141592653589793[Image from: Python Basics: Doty. S, (2008)] - Comparing StringsWhen 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 DsIf 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 DummiesDocument: Making sure others can read your programDesign: Making sure your program is solving the right problem and is organized so that it's efficient and potentially reusableDebug: Making sure your program doesn't have any mistakes in it and that it responds appropriately when given wrong inputLesson 1. Lets Dive Into The Code Example 1: Numerical Input.pyI 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 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.pyExample 3: HangmanBySaagarJagatia.pyI 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. HangmanBySaagarJagatia.pyThis 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.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!ProjectTry 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 . Here you will find many useful links to documentation.Lesson 2. Understanding the Python Library: ‘Import’ & Creating Modules Using & importing ModulesAs 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 mathimport 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 and it is possible to gain access to modules created by third parties via this link: . 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.Creating ModulesA 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 (): passprint (“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!ProjectNow try and create a module of your own and import it.Lesson 3. Understanding a Created LibraryThe 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 OutputsProjectNow 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. Lesson 4. Tkinter an Introduction - 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: or 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)Here is a Complete ExampleBelow is an example of code which was executed. It is a source taken from Grayson (2000) Code commentsFirst, 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 TkinterTkinter 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.Example 1: Helloworld.pyTo 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. ProjectTry 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)Example 2: SimpleCalculator.pyEven though the code may not look simple, this is a simple yet very effective program, Lundh (1999)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:Go through lesson objectives (2-5 minutes)Give an introduction to the topic (Python/ PyProcessing) (5-10 minutes)Set a task. (simple to begin with, then maybe a more advanced one for the pupils that can cope) (10-15 minutes)Give your students some time getting used to the code and various Syntax. (15 minutes) Give them some assistance with the online documentation available.Python - Pyprocessing - off the lesson with a few challenges, get the pupils into groups (and work on one machine) (10minutes)Conclude – review peer work. (5 minutes)N.B. Do note that bigger tasks may spread across two lessons.Tkinter Widgets TableWidgetDescriptionButtonA simple button, used to execute a command or other operation.CanvasStructured graphics. This widget can be used to draw graphs and plots, create graphics editors, and to implement custom widgets.CheckbuttonRepresents a variable that can have two distinct values. Clicking the button toggles between the values.EntryA text entry field.FrameA 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.LabelDisplays a text or an image.ListboxDisplays a list of alternatives. The listbox can be configured to get radiobutton or checklist behavior.MenuA menu pane. Used to implement pulldown and popup menus.MenubuttonA menubutton. Used to implement pulldown menus.MessageDisplay a text. Similar to the label widget, but can automatically wrap text to a given width or aspect ratio.RadiobuttonRepresents 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.ScaleAllows you to set a numerical value by dragging a "slider".ScrollbarStandard scrollbars for use with canvas, entry, listbox, and text widgets.TextFormatted text display. Allows you to display and edit text with various styles and attributes. Also supports embedded images and levelA container widget displayed as a separate, top-level window.Font Style OptionsOptionTypeDescriptionfamilystringFont family.sizeintegerFont size in points. To give the size in pixels, use a negative value.weightconstantFont thickness. Use one of?NORMAL?or?BOLD. Default is?NORMAL.slantconstantFont slant. Use one of?NORMAL?or?ITALIC. Default is?NORMAL.underlineflagFont underlining. If 1 (true), the font is underlined. Default is 0 (false).overstrikeflagFont strikeout. If 1 (true), a line is drawn over text written with this font. Default is 0 (false).Source - (2012)Tk Option Data TypesanchorLegal values are points of the compass: "n", "ne", "e", "se", "s", "sw", "w", "nw", and also "centre".bitmapThere 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".BooleanYou can pass integers 0 or 1 or the strings "yes" or "no" .callbackThis is any Python function that takes no arguments. For example:def print_it(): print ("hi there")fred["command"] = print_itcolourColours 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.cursorThe 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.distanceScreen 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".fontTk 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.geometryThis 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".justifyLegal values are the strings: "left", "center", "right", and "fill".regionThis 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.reliefDetermines what the border style of a widget will be. Legal values are: "raised", "sunken", "flat", "groove", and "ridge".scroll commandThis 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".Lesson 5. PyProcessing an IntroductionPyProcessing 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 . 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: 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’Once you have downloaded and installed Python 2.6, download and install Pyprocessing, which can be located at:. 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\site-packages\pyprocessing’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 60Now 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// // 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);## 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: 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: Example 2: Helloworld.pyNow 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.Example 3: Helloworldrot.py2241550157480The 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 canvasTextFont/Align – simple.Def = Definedef draw(): - this here tells us what we want the program to do.The ‘Hello World’ text is the result of the programmed code.00The 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 canvasTextFont/Align – simple.Def = Definedef draw(): - this here tells us what we want the program to do.The ‘Hello World’ text is the result of the programmed code.PyProcessing Questions and ChallengesNow 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:‘Hello my name is ________’‘Pyprocessing is cool!’‘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: . 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.ProjectHave 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!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: . This takes you through the following.The basicsHello WorldGeometric shapesColoursLine and border attributesContinuous applicationsInteractionsImagesTransformsAs 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:Go through lesson objectivesGive an introduction to the topic (Python/ PyProcessing)Set a task. (simple to begin with, then maybe a more advanced one for the pupils that can cope)Give your students some time getting used to the code and various Syntax.Give them some assistance with the online documentation available.Python - Pyprocessing - off the lesson with a few challenges, get the pupils into groups (and work on one machine)Conclude – review peer work.Pyprocessing Variables All of the functions listed below are used to program Pyprocessing, can be found at: 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: StructureProcessingPyProcessingDescriptiondraw()draw()a function of your program that is called for drawing a frameexit()exit()exits the applicationloop()loop()makes?draw()?be called periodicallynoLoop()noLoop()stops?draw()?from being called periodicallypopStyle()popStyle()restores the prior style settingspushStyle()pushStyle()saves the current style settingsredraw()redrawN/Arun()your program should call this to map the drawing window and start the event loopsetup()setup()a function of your program that is called automatically once by run()size()size()used to establish the dimensions of the drawing windowImageProcessingPyProcessingDescriptioncreateImage()createImage()creates an empty PImage objectfilter()screenFilter()applies a filter to the display windowimage()image()displays a PImage objectimageMode()imageMode()changes the semantics of the arguments of?image()loadImage()loadImage()loads an image into a PImage objectloadPixels()loadPixels()loads the current canvas data into screen pixelsupdatePixels()updatePixels()displays the data from screen pixelsget()get()returns a copy, a part of a pixel of the screenset()setScreen()sets a position of the screen with dataEnvironmentProcessingPyProcessingDescriptioncursor()cursor()Changes or shows the mouse cursor.delay()delay()stops the program from running for a specified timeday()day()returns the value of the current dayfocusedN/AframeCountframe.countNumber of frames drawn so far.frameRate()frameRate()Sets the number of times?draw()?will be called per second.frameRateframe.rateEstimated number of frames per second for the recent past.heightheightHeight of the drawing window in pixels.hour()hour()returns the value of the current hourlink()link()links to a webpagemillis()millis()returns the amount of milliseconds since starting a programminute()minute()returns the value of the current minutemonth()month()returns the value of the current monthnoCursor()noCursor()Inhibits the display of the mouse cursor.onlineN/Ascreenscreenholds the width, height and pixels of the display.second()second()returns the value of the current secondyear()year()returns the value of the current yearwidthwidthwidth of the drawing window in pixelsColourSettingProcessingPyProcessingDescriptionbackground()background()clears the drawing with a background colourcolorMode()colorMode()sets up the colour system (RGB or HSB) for specifying coloursfill()fill()specifies the colour for drawing filled shapesnoFill()noFill()makes shapes be rendered non-fillednoStroke()noStroke()makes shapes be rendered without their bordersstroke()stroke()specifies the colour for drawing lines and shape bordersnoTint()noTint()reverts to displaying images with their original valuestint()tint()sets the fill value for displaying imagesCreating & ReadingProcessingPyProcessingDescriptionalpha()alpha()returns the alpha (transparency) component of a colourblendColor()blendColor()returns the blending between two coloursblue()blue()returns the blue component of a colourbrightness()brightness()returns the brightness of a colourcolor()color()builds a colour value from its componentsgreen()green()returns the green component of a colourhue()hue()returns the hue of a colourlerpColor()lerpColor()returns a linear interpolation between two coloursred()red()returns the red component of a coloursaturation()saturation()returns the saturation of a colourShape2D PrimitivesProcessingPyProcessingDescriptionarc()arc()draws an arc of ellipseellipse()ellipse()draws an ellipseline()line()draws a line segmentpoint()point()draws a pointquad()quad()draws a quadrilateralrect()rect()draws a rectangletriangle()triangle()draws a triangle3D PrimitivesProcessingPyProcessingDescriptionbox()box()draws a parallelepipedsphere()sphere()draws a spheresphereDetail()sphereDetail()sets the level of detail used to render spheresCurvesProcessingPyProcessingDescriptionbezier()bezier()Draws a cubic Bézier curvebezierDetail()bezierDetail()Changes sampling rate of Bézier curvesbezierPoint()bezierPoint()Evaluates one coordinate of a point on a Bézier curvebezierTangent()bezierTangent()Evaluates one coordinate of a tangent of a Bézier curvecurve()curve()Draws a cubic Catmull-Rom curvecurveDetail()curveDetail()Changes the sampling rate of Catmull-Rom curvescurvePoint()curvePoint()Evaluates one coordinate of a point of a Catmull-Rom curvecurveTangent()curveTangent()Evaluates one coordinate of a tangent of a Catmull-Rom curvecurveTightness()curveTightness()Changes the tightness of Catmull-Rom curvesAttributesProcessingPyProcessingDescriptionnoSmooth()noSmooth()renders in non-antialiased moderectMode()rectMode()changes the semantics of the arguments of?rect()ellipseMode()ellipseMode()changes the semantics of the arguments of?ellipse()smooth()smooth()renders in antialiased modestrokeCap()N/AstrokeJoin()N/AstrokeWeight()strokeWeight()changes the thickness of linesVertexProcessingPyProcessingDescriptionbezierVertex()bezierVertex()adds a Bézier arc to the shapecurveVertex()curveVertex()adds a Catmull-Rom arc to the shapeendShape()endVertex()finishes the shapetexture()texture()sets a texture to be applied when drawingtextureMode()textureMode()changes how texture coordinates are evaluedvertex()vertex()adds a vertex to the shapeInputMouseProcessingPyProcessingDescriptionmouseButtonmouse.buttontells what mouse button is pressed.mouseClicked()mouseClicked()called when a mouse button is pressed and releasedmouseDragged()mouseDragged()called when a mouse is dragged with a pressed buttonmouseMoved()mouseMoved()called when a mouse is moved with buttons pressedmousePressed()mousePressed()called when a mouse button is pressedmousePressedmouse.pressedtells whether a mouse button is pressedmouseReleased()mouseReleased()called when a mouse button is releasedmouseXmouse.xcurrent?x?position of the mousemouseYmouse.ycurrent?y?position of the mousepmouseXpmouse.xprevious?x?position of the mousepmouseYpmouse.yprevious?y?position of the mouseKeyboardProcessingPyProcessingDescriptionkeykey.charholds the char value of the most recently pressed keykeyCodekey.codeholds an int code of the most recently pressed keykeyPressed()keyPressed()called when a key is pressedkeyPressedkey.pressed()tells whether a key is pressedkeyReleased()keyReleased()called when a key is releasedkeyTyped()keyTyped()called when a non-code key is pressedTextProcessingPyProcessingDescriptiontextAlign()textAlign()changes the text alignment attributescreateFont()createFont()creates a fonttextFont()textFont()sets the received font as current fonthtmlText()htmlText()draws the html text at the given positiontext()text()draws the text at the given positiontextSize()textSize()changes the current font sizetextWidth()textWidth()returns the width of the received string rendered in the current fonttextAscent()textAscent()returns the ascent of the current fonttextDescent()textDescent()returns the descent of the current fontMathProcessingPyProcessingDescriptionPVectorPVectora class used to describe two or three dimensional vectorsnoise()noise()returns the perlin noise value at specified coordinatesbinary()binary()converts a value to a string in binary notationhex()hex()converts a value to a string in hexadecimal notationunbinary()unbinary()converts a string in binary notation to its decimal valueunhex()unhex()converts a string in hexadecimal notation to its decimal valuebyte()byte()converts a char or int to its byte representationconstrain()constrain()returns the constrained value according to the received parametersdist()dist()returns the Euclidean distance between two pointsmap()map()re-maps a number from one range to anothermag()mag()returns the magnitude of a vectorlerp()lerp()returns a interpolation between two numberssq()sq()returns the square of a valueTransformProcessingPyProcessingDescriptionapplyMatrix()applyMatrix()multiplies the current transformation matrix by a given matrixgetMatrix()getMatrix()returns the MODELVIEW matrixpopMatrix()popMatrix()discards the current (top) matrix from thetransformation matrix stackprintMatrix()printMatrix()prints the current transformation matrixpushMatrix()pushMatrix()pushes a copy of the current matrix onto the transformation matrix stackresetMatrix()resetMatrix()sets an identity matrix as the the current transformation matrixrotate()rotate()rotates around a given axisrotateX()rotateX()rotates around the?x?axisrotateY()rotateY()rotates around the?y?axisrotateZ()rotateZ()rotates around the?z?axisshearX()shearX()shears a shape around the?x?axisshearY()shearY()shears a shape around the?y?axisscale()scale()performs a scale transformationtranslate()translate()performs a translation transformationLights, CameraLightsProcessingPyProcessingDescriptionambientLight()ambientLight()adds an ambient light sourcedirectionalLight()directionalLightadds a directional light sourcelightFalloff()lightFalloff()sets attenuation factors for next light sourceslightSpecular()lightSpecular()sets specular coefficients for next light sourceslights()lights()turns on lighting and default light sourcesnoLights()noLights()turns off lightingnormal()normal()sets the normal vector for subsequent verticespointLight()pointLight()adds a point light sourcespotLight()spotLight()adds a spot light sourceCameraProcessingPyProcessingDescriptionbeginCamera()N/Acamera()camera()sets the camera transformationendCamera()N/Aortho()ortho()sets an orthogonal projectionperspective()perspective()sets a perspective projectionprintCamera()printCamera()prints the current transformation matrixgetProjection()getProjection()returns the PROJECTION matrixprintProjection()printProjection()prints the current projection matrixCoordinatesProcessingPyProcessingDescriptionmodelX()modelX()returns the screen?x?coordinate of given object coordinatesmodelY()modelY()returns the screen?y?coordinate of given object coordinatesmodelZ()modelZ()returns the screen?z?coordinate of given object coordinatesN/AmodelXYZ()returns the screen coordinates of given object coordinatesscreenX()screenX()returns the screen?x?coordinate of given object coordinatesscreenY()screenY()returns the screen?y?coordinate of given object coordinatesscreenZ()screenY()returns the screen?z?coordinate of given object coordinatesN/AscreenXYZ()returns the screen coordinates of given object coordinatesMaterial PropertiesProcessingPyProcessingDescriptionambient()ambient()sets the ambient properties of the next verticesemissive()emissive()sets the emissive properties of the next verticesshininess()shininess()sets the shininess property of the next verticesspecular()specular()sets the specular properties of the next verticesPyglet Package – Extension taskIf you are asked, by IDLE to have Pyglet installed onto your machine when importing ‘Pyprocessing’ go to, 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.914400topNow 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.). 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 advancesSimple textImageGamesMulti-mediaHTMLExamples of which can be found in the ‘pyglet-1.1.4’ folder. Below are some program examples. (source on page 69) ProjectHave a look at the source code of some of the programs above; can you make/adapt any of these files?Lesson 5: Python Challenges QuestionsThis 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.Code a star using logo in Python (8 sided star)When programming a game of ping pong, what are the main classes (components) needed?Code a small simple shape (using Python 2.x – via the graphics module)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?Refer back to lesson 3 – “Understanding a created Library”Example code in answers section – source Price (2012)Note for this question you may need to use Python 2.x Create a simple calculation program – convert Celsius to Fahrenheit.You will need to know how to work out the difference between both. 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.Python Challenges Answersimport turtlet = turtle.Pen()for x in range(1,9): t.forward(100) t.left(225) 2.) Classes: Ball, Paddle, Wall3.) [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)r.draw(win)# Now let's try to output some texttext = Text(Point(250,250), 'Hello');text.setSize(20);text.draw(win)# now infinite loop to move a shapewhile 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 positiontext.setText(str(mouseLocn.getX()) + '\n' + str(mouseLocn.getY()) )# waits for mouse click to close windowwin.getMouse()win.close()main()]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 circlefill(255,255,0)stroke(0,255,255)strokeWeight(4)myCircle(100,100,50)# Now let's move the circle to the rightx = 100while x < 350:x = x + 20wait(1)myCircle(10+x,10+x,10)# check for a mouse click to interrupt (still Zelle)# really must fix thisif win.checkMouse() != None:win.close()# 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 thoughtwin.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'; ]Sleep program [ from time import sleepprint("We'll start off by sleeping 5 seconds")# make the program sleep for 5 secondssleep(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!" )]AppendixDebugging1.[# epdb1.py -- experiment with the Python debugger, pdba = "aaa"b = "bbb"c = "ccc"final = a + b + cprint final]2. Insert – import pdb3. 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, pdbimport pdba = "aaa"pdb.set_trace()b = "bbb"c = "ccc"final = a + b + cprint 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" )print( "2 Circle" )print()# 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 randomnum = 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') ]Example 3: HangmanBySaagarJagatia.py [import randommistakes = 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 fromword = random.choice(potentional_words)letters = list(word)print("") #making it look niceif word == "print": blankedword = str("________") print("The Word Has 5 Letters In It. Guess What It Is")elif word == "import": blankedword = str("________") print("The Word Has 6 Letters In It. Guess What It Is")elif word == "python": blankedword = str("________") print("The Word Has 6 Letters In It. Guess What It Is") #tells the user how many letter they need to guesselif word == "rossum": blankedword = str("________") print("The Word Has 6 Letters In It. Guess What It Is")elif word == "idle": blankedword = str("________") print("The Word Has 4 Letters In It. Guess What It Is")elif word == "shell": blankedword = str("________") print("The Word Has 5 Letters In It. Guess What It Is")print("")guessedletters = list(blankedword)while(mistakes != 7): #if they make 5 mistakes then the loop stops 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" 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...") #if they make a mistake then it adds one to their mistakes print("You've Made", mistakes, "Mistakes") print("") 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...") 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)) 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...") #if they make a mistake then it adds one to their mistakes print("You've Made", mistakes, "Mistakes") print("") 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!") 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()]Example 2: SimpleCalculator.py[from tkinter import *def frame(root, side): w = Frame(root) w.pack(side=side, expand=YES, fill=BOTH) return wdef button(root, side, text, command=None): w = Button(root, text=text, command=command) w.pack(side=side, expand=YES, fill=BOTH) return wclass 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), '+') 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 importsize (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()]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 = 0def 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()]Something fun for class1 player pong[from tkinter import *import randomimport timeclass 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) 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 = -3class 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: 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 = Truetk = 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)] Source: Briggs (2012)ReferencesAbelson. H, (2012) Logo Foundation: What is Logo? [Online] Available from: , [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: . [Accessed on: 15/01/2013]Dayley. B, (2006) Understanding Python: Python Objects, Modules, Classes and Functions, In: Python Phrasebook: Essential Code and Commands. UK. SamsDoty. S, (2008) Python Basics. [Online] Available from: . [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: . [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: . [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: . [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: . [Accessed on: 21/01/2013]Maruch. A, Maruch. S, (2006) Python for Dummies, UK, John Wiley & Sons, pp. 36-65Massachusetts Institute of Technology (2012), Seymour Papert. [Online] Available from: . [Accessed on: 16/12/2012]Mertz. D, (2000) Charming Python: TK Programming in Python. [Online] Available from: . [Accessed on: 18/01/2013]Oudkerk. R, (2008) Addition of the Multi-prcessing package to the Standard Library. [Online] Available from: . [Accessed on: 15/01/2013]Pitrou. A, (2012). A Finger-Grained Import Lock. [Online] Available from: [Accessed on: 21/11/2012]Price. C (2012) Creative Computing: Learning to Code in Processing for P3007. Dissertation topic. 1st October. University of Worcester.PyProcessing. (2012) PyProcessing: A Processing-Like environment for doing graphics with Python. [Online] Available from: . [Accessed on:22/11/2012]Rossum. G, (2012), Python Tutorial, [Online] Available from: . [Accessed on: 29/10/2012]Rossum. G, (2012) Python Library Reference Manual, [Online] Available from: . [Accessed on: 29/10/2012]Rossum. G, (2012) Python Library Reference: Release 2.5 [Online] Available from: . [Accessed on: 21/11/2012]Shipman. J, (2013) Tkinter 8.5 Reference: a GUI for Python. [Online] Available from: . [Accessed on: 26/02/2013]Tkinter. (2013) Tkinter [Online] Available from: . [Accessed on: 25/02/2013] ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- how long should a mission statement be
- what is your personal mission statement
- creating a mission statement worksheet
- personal mission statement template
- how to write a good mission statement
- writing a mission statement worksheet
- my mission statements for college
- project in project management definition
- project goal and project requirement
- mission control project management
- project and project management
- project specialist vs project manager