Topic outline

  • Introduction

    If you need to install Python onto your home computer this little guide should help you.

    • Documentation

      Like all programming languages there is a HUGE amount of information and options.   Even if I had a brain capable of remembering everything about Python – which I don’t, we just don’t have the time to teach you everything so you need to be prepared to go and search for the answer – here is a link to the documentation page for python.

    • Things to remember

      • Lines that start with # are comments.  They help us remember what the lines below do and are a very useful way of maintaining programs.
      • The order of the lines is important – we refer to this as sequence.
      • The first line of code uses the input ( prompt ) built-in python function to prompt the user to enter something into the python prompt.  Whatever the user entered is stored into something called  name.  name is identifier given to a variable – you’ll learn more about these terms in the future.  Just remember for now that whatever is entered is stored in name.  Note also that the user could enter anything and that anything could also give rise to an error – we’ll learn more about errors in the future too.
      • The last line of code takes the value of name and prints it to the screen using our print function.
  • Getting Started

    Go to the download page and get yourself a copy that would work on your computer.   I’m using version 3.1.2 but you can and probably should use the latest version – hopefully they won’t do any major updates on us in the next 9 months!

    • Windows Version  http://www.python.org/ftp/python/3.1.2/python-3.1.2.msi – Double click on the downloaded file and just choose all the default options.  You should now have a new program folder in your start-menu called Python X.X where X.X is the version you just installed.  You want to run the IDLE (GUI) which will let you write and run your own python programs.
    • Mac Version - http://www.python.org/ftp/python/3.1.2/python-3.1.2-macosx10.3-2010-03-24.dmg – Double click on the download file and then again on the Python.mpkg file.  Follow through the onscreen instructions.  You want to run the IDLE.app from the Python Applications folder which will let you write and run your own python programs.
    • Unix – If you want to run Python on a unix machine then what you need to do will depend on the flavour of unix you are using.   Currently Ubuntu is one of the most popular flavours and so I will explain how to install it on the Desktop version (not to be confused with the Server version).  Now Python comes installed as standard but you may want to update it just incase and the easiest way to do that is to open a command terminal typing sudo apt-get install python.   Sadly IDLE does not so you will need to go to Applications > Add/Remove Programs and choose IDLE from the programming category.  You could probably also use sudo apt-get install idle.

    Now we can use IDLE to write and run our own programs in Python – happy days!

  • Simple Hello Program

    Open the IDLE application on your computer.  The window that opens will look like a Command Line, Dos or Bash prompt.  Click next to the prompt which should look like >>>and type the following line before pressing return.  What happens?

    print ('Hello World')

    Excellent, the computer has just processed the statement you entered.  Print ( expression )is a built in python function that prints the expression given to the screen.

    Try entering something like:

    3 + 4

  • Programs longer than one line

    One line programs are very rare and we often would like to save the programs we write so we need a slightly better method.  Go to File > New Window – you should now see a blank window.  This is not a python prompt like before but a blank file rather like Windows Notepad or Mac Textpad.   Copy the following code into the window and save it into your programming folder as helloworld.py.

    # hello.py 
     
    #  Get the user's name and print a friendly hello
    name = input("Please enter your name: ") 
     
    print ("Hello", name, "- good to see you!")

    The lines starting with # are comments. Now once you have saved this file try clicking on Run > Run Module (or pressing f5) .

    What happens?

  • Repetition

    Repetition (aka Looping or Iteration) is the third of the three main programming prediciates.  Its allows us to repeat sections of code or operations on similar data.   There are two main types of Repetition or Looping:

  • Selection (Ifs and Case Switch)

    Ifs and Case-Switches allow us to make SELECTIONs in programming and to decide which direction we go in a program.

    It’s rather like waking up in the morning and thinking “Mmm, if its sunny today I will go to the beach otherwise I’ll stay at home and polish my shoes.”   In this example or are taking an input (the weather) and checking it against something (Sunny)  if the two match and therefore your statement is true then you do one thing otherwise you’ll do something else (the false branch).

    We could write this in pseudo-code like this:

    if weather is sunny then
     (true)  Go the beach 
     else 
     (false) Polish Shoes
    

    Basic Python IFs

    Or we could use proper Python code as in this following program which tests a number to see if its negative.

    x = int(input("Please enter an integer: "));
     
    if x < 0:
      print ('Negative');
    else:
      print ('Greater than or equal to zero');

    Note the first line is using our input function again but this time it is prefixed by a int function – this is important.  First, you need to be aware that because you have two open brackets you must have two close brackets in the right places!  Secondly, the int function serves to turn the value given by the user into a proper integer number.

    A Little Challenge: rewrite this program for yourselves but change it so it tests for positive and add appropriate comments for each line so your teacher can assess your understanding.

    Nested IFs

    Sometimes we need to ask more than one question in which case we use something call nested IFs.  The following example (in pseudo code) tests for positive and negative numbers.

     
    if num is less than zero then
      print negative 
    else if num more than than zero then
      print positive
    else 
      print it's zero !
    

    Now rather than using else if in Python we have to use the reserved keyword elif.

    Another little challenge: try and rewrite the program above in proper Python code with comments.

  • Sub Routines

    A Sub Routine is a small self-contained section of code that completes a task or process.  If you think about the theory of modular programming where you end up with small solvable problems – these are the sub-routines that together make up the program.  There are a number of advantages of using sub routines:

    • You can reuse your code :-  in a game a player will take many turns and therefore it makes sense to have a sub-routine that deals with player-turns( ).  Likewise you’d need to check if someone has won many times and therefore a iswinner( ) subroutine would be useful.  Notice that subroutines are written with normal brackets following them.
    • It makes your program easier to maintain:-  If you only have one place in your program where you write to a file and that process needs to change you only have to maintain one section of code.
    • If you need a hashtable routine and have already written one it’s very easy to cut and paste the routine from one program to another.

    Earlier we said that subroutines are written with trailing brackets.  This is so we can pass values to the subroutines, these inputs are known as parameters or variables e.g. getSquareArea( sidea, sideb)

    When is comes to returning values there are two types of Sub Routine (Procedures and Functions).  Procedures don’t return values they just do something.   Functions (like Maths ones) do return values using the return keyword.

    In Python, like many modern languages, we don’t differentiate between procedures and functions we just have functions.   To create a function we use the def keyword e.g.

    def getSquare( sidea, sideb)
      return sidea * sideb

    One of the frequent questions regards to returning values from routines is how to return more than one value.   Python has a very useful feature that allows us to create a tuple (type of array) on the fly e.g.

    def getSquareData ( sidea, sideb)
      perimeter = sidea + sideb + sidea + sideb
      area = sidea * sideb
      return [ perimeter , area ]

    Note: return perimeter, area and return (perimeter,area) would also work.

    Last snippet :-  Python allows you to define default values for your routines so you could declare our getSquare routine as:

    def getSquare( sidea = 0, sideb = 0)

  • Topic 7