CS21 : Break it up


https://docs.google.com/presentation/d/1iwMTKSaGwtVE6AbqDMyq85l1KseRfE2NAF9wufMgYiM/preview
A detailed look at the principles of decomposition and how we can practically apply these principles in a programming context to help us solve problems quicker and more efficiently.

We are learning ...
  • How to take a structured approach to problem solving
So that we can ...
  • Break a problem down into smaller parts (subroutines) and solve each one separately
  • Understand the difference between a function and a procedure
  • Describe the use of parameter passing and return value to transfer data between subroutines
  • Understand the concept of and use local and global variables effectively
  • Describe the benefits of using subroutines in programs
  • Use predefined procedures and functions
  • Convert simple code snippets into subroutines

CGP The Revision GuidePage 33, 54, 55
CGP Exam Practice WorkbookPage 40, 62, 63

# Get Ready.png

Activity 1 Practical decomposition    I   O   A   E 

In previous topics, we've considered how we can break down a problem into smaller parts. This is called decomposition. Often, decomposition makes problems easier to solve because we solve the smaller, easier problems first before we combine the smaller parts into one big solution.

Hangman

We've all played hangman before on paper, but what about a writing a computer program to do it?



Task 1.1 What would you like your hangman program to do?
Where we think about the features of a hangman program


With a partner

Discuss the features of a hangman program. Try to make the game as complex as possible (but not too complex!), by considering the following ...
  • Where will you store you list of words to choose from?
  • Will there by different words for different difficulty games?
  • How will you manage the players?
  • How will you manage turn-taking?
  • How will you store and display the different hangman images?
  • How will you store and display how many letters have been used?
  • How will you store and display which letters have been guessed correctly in the word?
  • How will you keep track of the score?
  • When will your program stop?
  • What happens if you want to stop the game and carry on later?
  • Could you keep a list of high scores?

Ah, yes, decomposition makes sense!

In your notebooks / on paper

Plan your game. Write one or more algorithms for all or part of the game in any way you see fit (written, structured English, pseudocode or flowchart) but remember to work together and use all the skills you've learnt in the course so far to help you ...
  • Variables / Constants / typecasting and conversion
  • Lists and dictionaries
  • Basic text file and binary file handling (open, read, write, append, close)
  • Using records to store data (CSV files)
  • Selection (if statements)
  • Iteration (for and while loops)
  • String handling / manipulation
  • Asking for input and displaying output
  • Arithmetic operators (addition, subtraction, multiplication, float division, modulus division, exponentiation)
  • Boolean (and, or, not) and comparison operators
  • Random number generation
  • Validation and verification routines
  • Authentication routines
Sure you have!


Now that we have some ideas on how our game might work, we can start to plan our solution using a special diagram called a structure chart or hierarchy chart.


Task 1.2 Structure chart
Where we learn how to build a structure chart for our hangman program


This is my attempt at the highest two levels of the structure of the hangman game ...

https://drive.google.com/file/d/0B83yXMOilskaSVVhWjJ6QWx2Ylk/preview
Click to engage

Each subsequent level breaks down the level above into a sequence of smaller and smaller tasks. Hopefully, each task gets easier and easier to solve. Remember, this is called decomposition or thinking procedurally.

In your notebooks / on paper

Try to complete at least the next level down for the four Level ONE problems; INITALISE, SETUP, PLAY and FINALISE. Think about what is involved in each problem and how you can design a simpler, step-by-step solution for each one. Draw each one separately - as a subprocess.


Activity 2 The theory of subroutines   I   O   A   E 

In some of the previous topics (especially the ones on file handling and databases), I showed you how to use a structured approach to programming by splitting down the original problem into stages which represented the different parts of the algorithm and then use subroutines (def) to code each part.

A subroutine is a programmatic way of breaking down a large problem into smaller, self-contained, reusable chunks. You can think of a subroutine as a 'black box' with a specification (how it operates) and an interface (how we interact with it). All subroutines have a signature which is defined by it's name and a combination of it's parameters (things we tell the subroutine) and it's return values (things which it tells us).

Subroutines interrupt program flow, but for good reason!

There are two types of subroutine ...
  • Procedures - Sometimes take parameters but never return values
  • Functions - Always take parameters (could be default) and always return values

Procedures

Procedures are subroutines which reliably perform some task, sometimes taking parameters but never returning an answer after they have finished executing. A procedure might generate output when it runs, but will not return that output for further processing.


Task 2.1 Real life procedures
Where we practice using real life procedures



In pairs

You will be given a set of cards. On one side is the name of a procedure which I'd like you to carry out. Some of the procedures also accept parameters which give the procedure information about how to carry out it's task. They are all designed to achieve some purpose but none of them give you anything back after you have completed them - they return no value.

In your notebooks / on paper

Reflect on, and write about, what you have found out from this activity.


Functions

Do you recognise the following functions ...
  • sin(n)
  • cos(n)
  • tan(n)
... which you must have met before in maths (unless you were asleep). A function always takes one or more parameters (even if they are default parameters) and always returns an value / answer. Therefore, functions must always been used as part of an assignment operation.

variable = function(parameters)


Task 2.2 Function machines
Where we learn about simple function machines


On the worksheet

Download, print and complete the worksheet, 'Function Machines'. Look carefully at the relationship between the mathematical functions and the stated functions in Python.


Implementing subroutines in Python

In Python, we use the def keyword (stands for define) to declare subroutines (both procedures and functions). 

https://drive.google.com/file/d/0B83yXMOilskaWnVjT3pFXy1aNGc/preview
Click to engage

Immediately following the def keyword is a subroutine name and an optional list of parameters which declare the initial (and sometimes default) variable values used in the subroutine_body.

We include the return statement to designate the subroutine as a function, otherwise it is technically a procedure. Remember, that if we call a function, we need to make sure it is only used as part of an assignment statement. So ...

variable = function(parameter*)   # Correct
function(parameter*)              # Wrong

variable = procedure(parameter*)  # Wrong
procedure(parameter*)             # Correct


Go for it!


Task 2.3 Built in subroutines
Where we try out some of Pythons built in subroutines


There are two types of subroutine - built-in and user defined. Let's look at built-in subroutines first.

We use built-in subroutines literally all the time when we program in Python (or any other language) but don't even realise it. The following exercise demonstrates just a couple of the built-in subroutines in Python.


At the Python prompt

Type the following commands at the prompt, pressing the  ENTER  key after each one.

>>> print('I am a procedure','that can take','multiple parameters')
>>> output = print('I return no value')
>>> print(output)

These command demonstrate the behaviour of a procedure.

At the Python prompt

Type the following commands at the prompt, pressing the  ENTER  key after each one.

>>> length = len('I am a function that returns a value')
>>> print(length)

These commands demonstrate the behaviour of a function.

In your notebooks / on paper

Using these two examples to help you, explain the similarities and differences between a function and a procedure. Can you think of any other examples?

At the Python prompt

You can use the return values of one function as the parameters of another. Type the following commands at the prompt, pressing the  ENTER  key after each one.

>>> import math
>>> print(round(math.sqrt(45)))

In your notebooks / on paper

In this example, there are two functions and one procedure. Identify which ones are which and explain how the final answer is derived.

For your notebooks / folders

Look carefully at the following diagram which gives you a list of all the built-in functions in Python 3.4. Click on the image and print yourself a copy for your notebooks.

https://drive.google.com/file/d/0B83yXMOilskabW1iVEdoa19XV1k/view?usp=drive_web
Click to engage (and print a copy)

You can visit the original page by clicking here which might be a useful page to bookmark!

On the printout

You should see that some of the subroutines (Python calls them all functions!) are  highlighted  in yellow. These are the ones you have seen so far in the course. Underneath the table, list out the subroutines and describe what they could be used for.



Task 2.4 User defined subroutines
Where we make our own subroutines


This is where the fun begins. If you are not able to find a built-in subroutine which does the job you want, you can define your own using the structure we looked at earlier.



In a Python script

Copy the following into a script (ask your teacher if you don't know how to do this). Save the script with a suitable filename and press  F5  key to run it.

def doesNothing():
  pass

At the Python prompt

Let's call the subroutine to see what it does. Type the following and press the  ENTER  key.

>>> doesNothing()

Boring isn't it? This is a subroutine which takes no parameters, performs no processing and returns no value. "What's the point?" I hear you ask! Often, we use these stubs as placeholders for subroutines we have not yet implemented (so we don't forget to make them!)

In your notebooks / on paper

Using an example, explain the meaning of the term 'stub'.

In a Python script

Copy the following into a script. Save the script with a suitable filename and press  F5  key to run it.

def printTitle():
  print('Welcome to my program')
  print('---------------------')

At the Python prompt

Call the subroutine to see what it does. Type the following and press the  ENTER  key.

>>> printTitle()

This is an example of a simple procedure - a subroutine that carries out a task but returns no value for further processing. This procedure takes no parameters either - it's only useful for structuring code through decomposition (we'll see examples of this in a minute).

In a Python script

Copy the following into a script. Save the script with a suitable filename and press  F5  key to run it.

def welcome(name):
  print('Welcome, {0}! Nice to see you!'.format(name))

At the Python prompt

Call the subroutine to see what it does. Type the following and press the  ENTER  key.

>>> welcome('John')

This is an example of a procedure which takes a single parameter, in this case 'John' (don't forget the quotes!), does something useful with the parameter but does not return a value for further processing. Try calling the procedure which a different name to convince yourself how it works.

In a Python script

Copy the following into a script. Save the script with a suitable filename and press  F5  key to run it.

def welcomeTo(name,location):
  print('Hello, {0}, welcome to {1}!'.format(name,location))

At the prompt

Call the subroutine to see what it does. Type the following and press the  ENTER  key.

>>> welcomeTo('Sandra','Xanadu')

This procedure takes two parameters. Try running the script again changing the values for name and location. You can pass as many parameters as you like in the subroutine - as long as you are consistent in the number of parameters you
send and the number you expect to receive, you will be fine.

In a script

Copy the following into a script. Save the script with a suitable filename and press  F5  key to run it.

def addOne(number):
  number = number + 1
  return number

At the prompt

Call the subroutine to see what it does. Type the following and press the  ENTER  key.

>>> successor = addOne(5)
>>> print(successor)

This is an example of a function which takes one integer parameter, adds one to the value and returns the new value. Notice that we always need to call the function as part of an assignment statement because we expect the function to return a value. In this case, I have just printed the value of number but you might want to do other things with it.

Within the function, if we don't need to keep the variable number for anything, we can shorten the function ...

def addOne(number):
  return number + 1

Try calling this new function - the result will be the same!

There is no need to evidence what you have just been doing, but, by now, you should be ...




To test your understanding of practical, user-defined subroutines, try these. For each one, you should print out your script and evidence that you have tested it.

Programming challenges

Attempt the following challenges to demonstrate your understanding.
  • Create a Python script for each of the challenges using IDLE (File > New File), save it with a suitable filename.
  • When you have completed as many of the challenges as you can, evidence your work through a combination of screenshots and written explanations in a word processed document with a suitable header and footer. 
  • Remember to show the script and the output it generates.
EASY

Write a procedure called printHeight() which takes one float parameter, height, and prints out the message 'Your height is height' (obviously replacing height with the value of the parameter, height).

MEDIUM

Write a function called spaces() which takes one string parameter, sentence, and returns number of spaces in the string. Remember to call your function as part of an assignment statement.

HARD

Write a function called sum() which takes one parameter, a list of integers called sequence, and returns the sum of those numbers. You could use random.sample() function to generate your sequence! Remember to call your function as part of an assignment statement.



Converting simple code snippets into subroutines

But what about all those 'code snippets' you've learnt in the past topics? How can we rewrite them in a structured form? Firstly, you have to ask yourselves a couple of questions ...
  1. Does the 'snippet' rely on one or more values?
  2. Does the 'snippet' calculate one or more values?



Task 2.5 Some conversions of your own
Where we perform some subroutine conversions of our own


We have seen some very useful code snippets in ...
... which do not use structured techniques (subroutines).

Gather some snippets

Look back and choose one snippet from each section. Make sure you have a new copy of it in the folder you have created for this section.

Convert to subroutines in a Python script

Convert your snippets to subroutines and make sure you test them out to make sure they still work the same. Remember, the operation of the snippet should remain unchanged - it's the implementation that is different.


Activity 3 A menu system   I   O   A   E 

I've put this in it's own activity because it's one of the uses of subroutines that you'll probably use most often - creating a menu system for a program. You've seen me do this before in previous lessons but this is the theory ...


As part of my new home automation system, I want to create a Python script (because that's the language my robot speaks) to instruct my servant robot perform the following tasks ...
  1. Put out the bins
  2. Feed the cats
  3. Do the washing
  4. Water the plants
  5. Vacuum the house
Firstly, I create a structure chart to help me to clarify how I am going to decompose my problem ...

https://drive.google.com/file/d/0B83yXMOilskadXBHZW03SE42MXM/preview
Click to engage


Task 3.1 Analysing my menu system
Where we create a simple menu system



Download the Python script

Download the script, 'menu.py' and save it in a suitable place in your documents. Find the file, right click on it and choose 'Edit with ... > Idle' to open the script with Python.

Inspect the script with your shoulder partner

You should see two sections ... at the top, all the functions (starting with def) and at the bottom of the script, the program itself ...


Run the script

Convince yourself how it works by Rubber Ducking it with a programming partner. Then print out the script in colour (using Notepad++) so that can keep a copy in your folders / notebooks (you never know when you might need it!)

In a flowchart

Using suitable software (or on paper), draw a flowchart for this menu system. You only need to draw your flowchart for the main program (the section in the screenshot above) - but remember that the functions must be shown as subprocess boxes in your flowchart ...


Make sure you get your flowchart checked by your teacher.

Demonstrate your understanding in a Python script

Now it's your turn to create a menu system for your own servant robot. Use my template the help you and create your own model of the most important jobs that you would like your robot to do. My robot only tells me what it has done. Try extending your robots behaviour so that it actually does something (computationally) useful!

Let your shoulder partner and your teacher see what you have done.


Activity 4 Local and global variables   I   O   A   E 

The term variable scope is used to describe the availability of a variable to the code in your program.

There are two main scopes ...
  • Local scope : access to variables is limited the the subroutine in which they are declared. Local scope variables only exist for the duration of the subroutine call.
  • Global scope : variables are available to code inside and outside functions and exist whilst the program is running. Global scope variables can be declared inside functions but must be explicitly declared as global.

https://drive.google.com/file/d/0B83yXMOilskaZk5pY1FtWlNKOWs/preview
Click to engage


Task 4.1 Demonstrating variable scope
Where we learn about variable scope




Download the Python script

Download the script 'scope.py' and save it in a suitable place in your documents. Open the script in IDLE and read through it carefully with your shoulder partner. Can you see what I'm trying to achieve?

Now run the script

You will see a lot of output from this script which looks very similar. Print out the script and the output for your folders / notebooks. Write line numbers alongside each line in the script to enable to you continue with the task.

In your folders / notebooks

Answer the following questions in full sentences.

01.  State the values of J, K, L and M before calling any subroutines?
02.  State the line numbers in the script where they get their initial values.
03.  State the value of J inside subroutine a()?
04.  Explain why the value of J in the main program still 'Jackson'?
05.  State the value of K inside subroutine b()?
06.  Explain why the value of J in the main program changed from 'Kuwait' to 'Kuala Lumpur'?
07.  State the value of L inside subroutine c()?
08. Explain why the value of L in the main program still 'London'?
09.  Explain why the value of K in the main program has changed but the values of J, L and M haven't.
10.  Explain the meaning of the term 'variable scope'.


Activity 5 ... Back to Hangman   I   O   A   E 

Bet you thought I'd forgotten, didn't you! This extended task will help you to demonstrate that you understand how to structure solutions to problems using decomposition, using functions and procedures and variable scope.


Task 5.1 Hangman
Where we complete our hangman game



Download the Python Script

Download the 'hangman.py' script, the 'hangman.csv' file containing the hangman images and the 'words.csv' file which contains the words for the game. Save all of these scripts into the same folder or else the game will not work correctly. 

Have fun and play!

Now run the game and enjoy!

As a class

If possible, your teacher will take you through the entire script. As you work through it, write notes on the script to explain what the different parts of the script do. You will find literally loads of useful things in here which will help you with any other programs you have to write.

On the worksheet

Download the worksheet 'Understanding hangman' and complete the activities. Hand the worksheet in to your teacher for checking.

In a structure chart

Draw a structure chart for the Hangman game. Base your structure chart on the one that we met in the first part of the lesson and also on the one in Activity 3 where we created a menu system. If possible, check with your teacher before you carry on.

Extra features

Could you implement some extra features like ...
  • Another category of quiz questions (Easy)
  • A more complicated (i.e. longer) hangman image (Medium)
  • A way of guessing the whole word (Hard)

In (a) flowchart(s)

Create simple flowcharts for the Main Program and all the subroutines in the program. Remember to use subprocess symbols where a call to a subroutine occurs.


Assessment Task (Homework)

You have learnt a lot in this section but you will only be able to demonstrate your understanding by creating your own script. Using the menu template that you saw in Activity 3, the concept of subroutines and the Hangman program to help you, create a script which implements a simple calculator. The program should ...
  • Provide a menu for you to choose which operation you would like to carry out. Restrict this to addition, subtraction, multiplication and division.
  • Ask for the operands using the same function.
  • Display the answer in a suitable format.
  • Append the results of the calculation in a text file, maintaining a calculation history.

Grading rubric

MASTER : You have implemented a calculator script which saves history in a text file.
APPRENTICE You have implemented a calculator script with limited levels of modularity
NOVICE : You have attempted to implement a calculator script.

Click to download revision cards
https://docs.google.com/document/d/1q39aIZ50a8NZiE_ZSE1N7Ixh_sfnT0OyNlKNAY7Ic_A/export?format=pdf
Remember to print them single sided

# Flash cards.png
Click to load key word list to help you make your own flash cards 

https://goo.gl/forms/W0N5gfJZTkNuZApk2
Try to get 5/5!


Hungry for more?

If you didn't get chance to try out the 'Snippet to Subroutine' task above, there are tons of structured solutions to all the file handling snippets we saw in Keeping data safe, the sorting and searching snippets we met in Sorting and Searching, the validation and verification snippets we met in Validate and verify and the authentication snippets we saw in Authenticate ready for you to download.

Now is the time to collect together all the structured scripts into one place so you can find them and easily use them in solution to problems that you might meet, very, very soon! 

I've also created a tutorial to show you how to develop a simple structured script called Developing a Solution.