Skills Knowledge Enhancement - Coding

Installing Python, Pyscripter & PyGame

Install the 32 bit versions, whether you have a 32 or 64 bit machine.  Pyscripter is no longer supported and the latest version (v2.6.0) will not work with versions of Python that are higher than 3.4

  All the files you need are in "Dropbox\SKE\Python_and_Pygame Installation".

1.

 

Remove previous versions of Python, Pygame and Pyscripter.  If, during the installations, it asks you to repair, remove or re-install, choose remove.

2.

Install 32-bit Python using ‘python-3.4.4.msi’. During installation ensure the following are ticked:

a.

Install for all users

b.

Accept the default destination directory

c.

Customize the installation

i.

include the option to install pip.exe

ii.

Add Python Paths to the Environmental variables

3.

Log off or reboot and log back on, to ensure the Paths are set correctly

4.

Install PyScripter-v2.6.0 using ‘PyScripter-v2.6.0-Setup.exe’

5.

Update ‘pip’

a.

Open a command prompt (Start/WindowsSystem/Command Prompt)

b.

Type in to the command prompt  python -m pip install -U pip

6.

Stay in the command prompt and type pip install pygame to install Pygame

Test the overall installation by running ‘aliens.py’.  It will be in the examples folder, in the Python installation:                C:\Python34\Lib\site-packages\pygame\examples

example program aliens.py

  • Back to Top

  • Python Coding

    There are a number of free Python coding courses online. The 'Tutorials for Beginners' on the Hour of Code site will take you through the basic structures which are common to all programming languages. Here are some books that you may find useful in your coding pursuits!

    Introduction to Python

    Little Book Of Programming Challenges

    Python Programming Challenges Book 1

    Python Programming Challenges Book 2

    QuickPythonBook

    Michele Pratusevich has put together some Python graded coding challenges that also include a brief discussion of the techniques needed to derive the solution. WELL WORTH A LOOK! The site also has the solutions to each of the challenges which might save you, the teacher, valuable.

    Code Academy

    If you have never tried coding (programming) before you may like to start with an Hour of Code or Code Academy. Code Academy is a free, interactive website that can take you through the basics of many programming languages. Sign up and start coding!

    OCR Teaching Resources

    OCR, one of the big 4 awarding bodies (exam boards), have put together An Introduction to Python. If you have done any programming before, try this.

    OCR have also put together 20 'Coding Challenges' that should help with the development of all the skills necessary for tackling the GCSE (9-1) Computer Science Controlled Assessments. A solution template and Psudocode guide is also available on their website, in the Teaching and Learning Resources section.

    Python Tutor

    Python Tutor, created by Philip Guo, helps people overcome a fundamental barrier to learning programming: understanding what happens as the computer executes each line of a program's source code. Using this tool, you can write PythonJavaJavaScriptTypeScriptRubyC, and C++ programs in your Web browser and visualize what the computer is doing step-by-step as it executes those programs.

    Using Python

    A website that gives you practical experience in using Python to solve fun and interesting real-world problems. The side menu on this site will take you through Python fundamentals and also have solutions to some coding challenges. The solutions are password protected; ask me for the individual passwords or the master password.

    Three possible solutions to finding the mean of a set of numbers are Average v1, Average v2 and Average v3.

    Old School Resources

    If it's 'Old School' Python exercises that you're after then here are some that will take you through variable types, While and For loops and If..Then..Else.

    Controlled Assessment is common to all Computer Science schemes. One of the OCR controlled assessments (for the old A453 specification) concerns the development of a teaching tool for the assessment of students' arithmetic skills, recording their marks and finally presenting the teacher with an analysis of the results. A suite of programs that could help with the development of the skills that are needed for the completion of the CA Tasks is 'Work up to A453 with exercises'. At the end there are some exercises leading to Picture Bingo and regular bingo.

  • Back to Top

     

  • Arrays, Lists, Tuples and Dictionaries

    The following notes summarise these data structures but a more comprehensive document about Arrays, Lists, Tuples and Dictionaries can be downloaded or a good explanation can be found at :

    Arrays

    http://www.i-programmer.info/programming/python/3942-arrays-in-python.html.

    One of the most fundamental data structures in any language is the array. Python doesn't have a native array data structure, but it has the list which is much more general and can be used as a multidimensional array quite easily.

    List basics - Square Brackets

    A list in Python is just an ordered collection of items which can be of any type. By comparison an array is an ordered collection of items of a single type - so in principle a list is more flexible than an array but it is this flexibility that makes things slightly harder when you want to work with a regular structure. A list is also a dynamic mutable type and this means you can add and delete elements from the list at any time.
    To define a list you simply write a comma separated list of items in square brackets:
    months = ['January','February','March','April','May','June',\
    'July','August','September','October','November','  December']

    Notice that a back slash can be used to continue one line onto the next to make it easier to read in the editor

     

    At first it may appear that a Python List is an array but you can only add items to the end of a List using append, you can't assign a value to a List if the element in the List doesn't already exist.

    Eg. This WILL NOT WORK because there are no existing elements in the List!
    myList=[ ]
    print(myList)
    for i in range(10):
        myList[i]=i
    print(myList)

    but this WILL because it is adding elements on to the END of the List.
    myList=[ ]
    print(myList)
    for i in range(10):
        myList.append(i)
    print(myList)

    NB If elements already exist in the List, you CAN change their contents
    myList = [5, 17, 12, 66, 103, 2, 9, 8, 5]
    print(myList)
    myList[3]=29
    print(myList)

    Tuples - Ordinary Brackets

    http://www.tutorialspoint.com/python/python_tuples.htm

    A tuple is a sequence of immutable (unchangeable) Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use 'round' brackets, whereas lists use square brackets.

    Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between brackets also. For example −

    tup1 = ('physics', 'chemistry', 1997, 2000)
    tup2 = (1, 2, 3, 4, 5 )
    tup3 = "a", "b", "c", "d"

     

    Dictionary basics - Curly Brackets

    http://www.i-programmer.info/programming/python/3990-the-python-dictionary.html

    A dictionary is a data structure in Python that allows data to be stored in a way that allows it to be found very quickly. Data is stored using a unique 'Key' followed by the data associated with that key. The structure is not limited to one data type but it can contain a mixture of all data types.

    age={}      /creates an empty Dictionary
    age["Lucy"]=19     /put 19 into the dictionary whose key is 'Lucy'
    print age["Lucy"]     /output Lucy's age

    An example of a dictionary in Python.

    OCR A453 - Maths Quiz - Task 3 solution incorporates the above data structures.

  • Back to Top

  • Sorting Techniques

    There are a number of different sorting algorithms and the one to choose depends is dependent upon the data that you wish to sort. This video gives an indication of the relative speeds of some of sorting techniques.

    Bubble Sort

    A Bubble Sort passes through a list of data (a List in Python but referred to as an Array in most other languages) and compares adjacenet items in the list. If they are NOT in the correct order, it swaps the two items; if they are in the correct order it does nothing. After each comparison it moves to the next item in the list and compares the next two adjacent items unitl it reaches the end of the list. After the pass through the list is complete, if there has been at least one swap, the precess is repeated from the beginning of the list. The precess ends when it completes a pass and it has NOT made any swaps. Here is a site that illustrates the Bubble Sort process with some graphics and here is a Python example:

    bubbleSort

  • Back to Top

  • Insertion Sort

    An ascending insertion sort successively takes the next element to be sorted and places it in its correct position in the sorted part of the array.

    To achieve this we need to logically divide the array into two parts – an unsorted part and a sorted part. At the beginning of the process, the first element becomes the sorted part of only one element and the remainder of the array is the unsorted part.

    A 'pointer' moves through the unsorted part taking each array element in turn and looks for the correct place to insert it in the sorted part. It does this by comparing this unsorted element with the element at the end of the sorted portion of the array. If it is NOT the correct position, the sorted array element shuffles across one place and the comparison is again made with the next item in the sorted list (working backwards through the sorted list). This process is repeated until the correct position is found. As soon as the correct position is found in the sorted section, it places the unsorted elemnt into that place. The 'pointer' then moves on in the unsorted portion of the array and the process is repeated.

    If that made sense to you, you must already know how this works! If it didn't make much sense, watch this CS50 clip and then read it again.

    Here's a Python implementation of the solution suggested in the video.insertionSort

    Here's the dance!

  • Back to Top

  • Merge Sort

    A YouTube video demonstrating a Merge sort.

    merge_sort

  • Back to Top

  • Recursion

    Recursion is a tool a programmer can use to invoke a function call on itself. Fibonacci sequence is the textbook example of how recursion is used. A musical example is the nursery ryme, '10 Green Bottles hanging on the wall'.

    greenBottles
  • Back to Top

  • Python Formatting

    http://www.python-course.eu/python3_formatted_output.php

  • Back to Top

  • Error Handling

    Unfortunately errors are a part of programming that cannot be avoided and they must be taken extremely seriously. The first step in avoiding errors is to be aware of them, and their differing types, and then employ strategies for eliminating them or handling any exceptions that can be predicted but not avoided during execution. Complete this sheet of notes in your own words to summarise error handling.

    Python's error trapping uses 'Try/Except' to detect and handle a range of run-time errors (watch a video produced by an unkown practicing teacher)

    Here is an example of a Trace Table. Trace table example for Python 'Months of The Year'.

  • Back to Top

  • Python I/O Methods

    Creating text files and reading from text files can be seen on a YouTube video (the URL is in the header of the example Python program) and there are some notes here.

  • Back to Top

  • Python GUI - tkinter, PyGame and easygui

    TKINTER

    The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems.

    A series of 14 tkinter tutorial videos can be found on YouTube. The presentation style can be a little tedious but the content and explanation is a good place to start tkinter. There is also a site taking you through the fundamentals of tkinter, without videos and tedious commentary!

    PYGAME

    Pygame is a cross-platform set of Python modules designed for writing video games. These are NOT part of standard Python, they have to be installed after successfully installing Python. Pygame includes computer graphics and sound libraries designed to be used with the Python programming language. The Pygame installer can be downloaded from here but it is easier to add Pygame to Python using pip (see Installing Python, Pyscripter & Pygame).

    A series of excellent Pygame tutorials written by Lorenzo E. Danielsson, that have been updated for Python 3.3, can be found here:

    Tutorial 1, Tutorial 2, Tutorial 3, Tutorial 4, Tutorial 5, Tutorial 6, Tutorial 7, Tutorial 8, Tutorial 9

    For the last question in the exercises of Tutorial 2 you may need a hint sheet.

    A WORKING GAME in Pygame

    If you want to skip to a working copy of the worm game, you can copy and paste the code from this text file. Save the program but before running it you will also need to copy the chomp.wav file into the folder where the program is saved. Now try to alter the speed of the worm, to make the food bigger (10 instead of 3) and to make the speed the worm up a little after it's eaten some food. Have a play!

    EasyGUI

    This is a module for very simple, very easy GUI programming in Python. EasyGUI is different from other GUI generators in that EasyGUI is NOT event-driven. Instead, all GUI interactions are invoked by simple function calls. EasyGui provides an easy-to-use interface for simple GUI interaction with a user. The full syntax for each function call can be found on the EasyGUI tutorials site.

    EasyGUI is not native to Python and so you will have to place easygui.py into the same directory as your python programs and import the easygui module into your python scripts.

  • Back to Top

  • JavaScript

    The JavaScript programming language, developed by Netscape, Inc., is not part of the Java platform. JavaScript does not create applets or stand-alone applications. In its most common form, JavaScript resides inside HTML documents, and can provide levels of interactivity to web pages that are not achievable with simple HTML.

    Key differences between Java and JavaScript:

    • Java is an OOP programming language while Java Script is an OOP scripting language
    • Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only
    • Java code needs to be compiled whilst JavaScript code is all in text
    • They require different plug-ins

     

    JavaScript Can Change HTML

    JavaScript is the default programming language of HTML and the internet and it can be used to program the behaviour of web pages.  There are many online courses available but one of the easiest (and free!) courses is at http://www.w3schools.com/js/default.asp

    Any number of JavaScripts can be placed in the <body> and the <head> sections of an HTML page but the JavaScript code must be inserted between <script> and </script> tags.  Although more than one script block is allowed, keeping all code in one place is always a good practice.  It is also better to place scripts at the end of the <body> element because it can improve page loading.

    Amongst other things, JavaScript can be used to change HTML Content, HTML Attributes, HTML Styles (CSS).  The script can be embedded in HTML files but if many different web pages use the same code, it is more practical to place the JavaScript code in external files (with the file extension of .js) and to call these files up using the src attribute.

    Try these out by looking at the JavaScript examples in w3schools website or follow the links in this text.

    Concentration Game

    At a recent CAS Hub meeting Jan Lawton of Staffordshire University presented 'JavaScript - Making the Web Behave'.

     Con Scr Shot

    This develops a Pairing Game using Javascript. Here is Jan's partially completed game and here is my version of the finished game. Try working through Jan's Powerpoint and complete the partial solution.

  • Back to Top

    VB.NET

    Visual Basic.NET has many similarities with its predecessor, Visual Basic 6, but it is vastly different and its functionality has more in common with C# than VB 6. The basic syntax does, however, remain very similar to the older VB: conditions, loops, procedures, sub-routines are declared and written in the same manner and both versions of VB are case-insensitive.

    Microsoft do provide a free version of their VB.NET IDE, called Visual Studio Community 2015, which is available for downloading.

    The usual 'Hello World' example will introduce us to the IDE and allow us to interact with a console window.

    Hello Kitty will give us an app that performs similarly to the Hello Kitty example in App Inventor and this introduces us to Windows Forms. (Resources for Hello Kitty - meow.wav and kitty.png )

    More usefully, the WPF Applications example that displays a Times Table in a MS Window introduces us to Windows Presentation Foundation. It is a graphical subsystem for rendering user interfaces in Windows-based applications by Microsoft. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0. Rather than relying on the older GDI subsystem, WPF uses DirectX.

    A small challenge in problem analysis and implementation in an object-oriented computer programming language is a 4-function calculator. A functioning, but slightly flawed, solution can be imported into Visual Studio from Dropbox.

    Lynda.com is a superb resource for learning any coding or scripting languages and I believe it is freely available to all Staffs University students. One of the programs that it uses to take a learner through VB.NET is Coderunner. A simple WPF App that allows a user to easily test VB constructs.

    Times Ed has a bank of resources that teachers have supplied for other teachers to use. Check out Mr Grimshaw's 'Programming Guide with Visual Studio.

  • Back to Top

    PHP and SQL

    What is PHP?

    PHP was originally an acronym for Personal Home Pages, but it is now a recursive acronym for “PHP: Hypertext Preprocessor”. It is a widely-used, open source scripting language that is free to download and use!

    PHP scripts are executed on the server and so the 'client' never sees any PHP script, only the results of the executed PHP. The results are returned to the client in HTML format.

    PHP Diagram

    "An Introduction to PHP" can be downloaded here.

    PHP, SQL Example

    Proof of concept:
    For one day only, you can create live web pages onto my AGB Online website. If these pages contain php script, that script will run when the page is accessed in a browser. The script is run on the host computer of my web server and not on the computer that is accessing the page. The user only sees the result of the php script.

    The notes that will take you through the process are here.

    Something more realistic - a Form:
    An HTML form can be created that will accept user input and 'post' the data into another page that can be handled with some php code. The data that is posted is NOT written to an SQL database, it is just available to the page that it is posted to.
    Try this 'StudentDetailsForm0'. When the form is 'submitted', it will automatically move to the handling page, 'HandleForm.php'.

    An improvement to the HTML form is to include some php that will post the data back to the same page that contains the form - itself! Try this 'StudentDetailsForm1' This same page has some php at the end that will show you what's been posted. 'StudentDetailsForm1a' has some code that will show you what data is associated with the page before the form has been 'submitted' and what is available after submission. 'StudentDetailsForm1b' corrects a problem with the 'Gender' field.

    Exploits of a Mom

    Error checking, validation and obligatory input: The problem with the form so far is that it will accept anything that is entered and it is possible for the site to be hacked if certain data is entered and it is that is sent to an SQL database. What's needed is some validation of the data and some error checking. This script also makes certain fields obligatory. Try this 'StudentDetailsForm2' Notice that if the submission rules aren't followed, error messages are shown but the form doesn't clear it's data. This allows the user to make corrections without having to retype everything! After a successful submission it is advisable to move to another page, otherwise the user may be tempted to re-submit the same data. This page re-directs to StudentDetailsShow1.php which shows the contents of a SQL database. This page does not yet add the input data to the database but 'StudentDetailsForm3' does!

    All checked? Add the input to an SQL database: This form does just that - 'StudentDetailsForm3' .

    The table below will help to explain the functioning of the 'Student Details Form'. Copy the table and explain in your own words what each term means.

    php Code Reference 1 Reference 2
    PHP Tutorial http://www.1keydata.com/php-tutorial/  http://www.w3resource.com/php/php-home.php
    PHP Tutorial - Forms http://www.1keydata.com/php-tutorial/forms.php  http://www.w3resource.com/php/form/php-form-handling.php 
    echo http://www.1keydata.com/php-tutorial/echo.php  http://www.w3resource.com/php/echo-print/echo.php 
    trim() http://www.1keydata.com/php-tutorial/trim.php   
    stripslashes() http://www.w3schools.com/php/func_string_stripslashes.asp   
    htmlspecialchars() http://www.1keydata.com/php-tutorial/htmlspecialchars.php   
    require_once() http://www.w3resource.com/php/statement/require_once.php   
    isset() http://www.w3resource.com/php/function-reference/isset.php   
    empty() http://www.w3resource.com/php/function-reference/empty.php   
    preg_match() http://www.tutorialspoint.com/php/php_preg_match.htm   
    filter_var() http://www.w3schools.com/php/php_ref_filter.asp  http://www.w3schools.com/php/func_filter_var.asp 
    FILTER_VALIDATE_EMAIL http://www.plus2net.com/php_tutorial/filter_validate_email.php  http://www.w3schools.com/php/filter_validate_email.asp
    mysqli Functions http://www.tutorialrepublic.com/php-reference/php-mysqli-functions.php  http://www.w3schools.com/php/php_ref_mysqli.asp
    mysqli_connect() http://www.phpgang.com/how-to-use-mysqli_connect-in-php_336.html  http://www.w3schools.com/php/func_mysqli_connect.asp 
    mysqli_connect_error()   http://www.w3schools.com/php/func_mysqli_connect_error.asp 
    mysqli_close()   http://www.w3schools.com/php/func_mysqli_close.asp 
    header() http://www.1keydata.com/php-tutorial/redirect.php  http://www.w3schools.com/php/func_http_header.asp 
  • Back to Top

  • Python Turtle

    “Turtle” allows you to give simple movement commands to a cursor. As it moves, it draws a line behind it, showing the path travelled. You can, therefore draw shapes very easily.

    “Turtle” is a python feature like a drawing board, which lets you command a turtle to draw all over it!

    Here are some examples.Spirographs

  • Back to Top

  • AppInventor

    App Inventor lets you develop applications for Android devices using a web browser and either a connected phone or emulator. The App Inventor servers store your work and help you keep track of your projects.

    The HelloPurr App is AppInventor's equivalent of 'Hello World' and a simplified set of notes and follow-up exercises are available here. More tutorials and challenges for App Inventor 2 (approximately 25) are available on the AppInventor website.

  • Back to Top

  • Blockly Games

    Blockly Games is a series of educational games that teach programming. It is designed for students who have not had prior experience with computer programming. By the end of the games, players are ready to use conventional text-based languages.

    Blockly Games is a Google project to encourage tomorrow's programmers. The games are designed to be self-paced and self-teaching. Blockly Games can be used both inside and outside the classroom. All code is open source, see the developer's website for more info or to download zip files for offline use.

  • Back to Top

  • Kodu

    Kodu is a visual programming language made specifically for creating games. It is designed to be accessible for children and enjoyable for anyone. The visual nature of the language allows for rapid design iteration using only an Xbox game controller for input (mouse/keyboard input is also supported). Kodu Download

  • Back to Top

  • Touch Develop

    This an interactive development environment and a visual programming language being developed by Microsoft Research.

    TouchDevelop is used to develop application programs for mobile devices, including smartphones and tablets. It can also be used on any computer which has a suitable web browser. In addition to its use as a tool for creating application programs, TouchDevelop has been used to teach programming and mobile device technology in schools,

  • Back to Top

  • Scratch

    Scratch is a multimedia authoring tool that can be used by students, scholars, teachers, and parents for a range of educational purposes from maths and science projects, including simulations and visualisations of experiments, recording lectures with animated presentations, to social sciences animated stories, and interactive art and music. Simple games may be made with it, as well. Viewing the existing projects available on the Scratch website, or modifying and testing any modification without saving it requires no online registration.

    Scratch allows users to use event driven programming with multiple active objects called "sprites". Sprites can be drawn from scratch in a simple editor that is part of the Scratch, or can be imported from external sources, including webcam.

    If you want to try it out now, go to scratch.mit.edu or download an offline version.

  • Back to Top

  • Hour of Coding

    Hour of Code™ is an opportunity for every student to try computer science for one hour.

    You can also teach the Hour of Code all year-round. Tutorials will work on browsers, tablets, smartphones, or "unplugged."

    A number of coding tutorials are available. Try the JavaScript!

  • Back to Top

  • Assembler and LMC

    Programming at the lowest level would invlove coding in binary but the next step up is to use a language where every binary instruction can be represented by one written statement, assembler. An online simulator that models a simple von Neuman architecture computer from the 1970's can be found at http://peterhigginson.co.uk/LMC/ . There is a more up to date model that is a very simplified ARM-like RISC simulator at RISC LMC.

    LMC Instruction Set


    Instruction
    Mnemonic
    MachineCode
    Load
    LDA
    5xx
    Store
    STA
    3xx
    Add
    ADD
    1xx
    Subtract
    SUB
    2xx
    Input
    INP
    901
    Output
    OUT
    902
    End
    HLT
    000
    Branch if zero
    BRZ
    7xx
    Branch if zero or positive
    BRP
    8xx
    Branch always
    BRA
    6xx
    Data storage
    DAT


    xx refers to an Address

     

    Vixaxsolutions has an LMC section which provides a good introduction to the LMC simulator, with a number of simple example programs. Copy the code into the LMC and follow their working. Also try changing some of them slightly to extend their function. Do they all work?

    Try these: Square Numbers, Division, Fibonacci

     

    Here is a lesson for multiplying two numbers together which can be found at http://www.canyoucompute.co.uk/214-lmc-multiply.html. A flowchart for the solution and the solution is also included. The 'canyoucompute' is well worth investigating for all aspects of computer science, not just Assembler.

  • Back to Top