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 ...
So that we can ...
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 Discuss the features of a hangman program. Try to make the game as complex as possible (but not too complex!), by considering the following ...
Ah, yes, decomposition makes sense! 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 ...
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 ... 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. 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.
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 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 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. Reflect on, and write about, what you have found out from this activity. Functions
... 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 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). 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 ...
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. 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. 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. 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? 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 this example, there are two functions and one procedure. Identify which ones are which and explain how the final answer is derived. 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. Click to engage (and print a copy) You can visit the original page by clicking here which might be a useful page to bookmark! 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. 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 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!) Using an example, explain the meaning of the term 'stub'. 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('---------------------') 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). 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)) 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.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)) Call the subroutine to see what it does. Type the following and press the ENTER key. >>> welcomeTo('Sandra','Xanadu') 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 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. Attempt the following challenges to demonstrate your understanding.
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 ...
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). 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 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.
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 ...
Firstly, I create a structure chart to help me to clarify how I am going to decompose my problem ... Task 3.1 Analysing my menu system Where we create a simple menu system 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. You should see two sections ... at the top, all the functions (starting with def ) and at the bottom of the script, the program itself ...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!) 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. 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.
The term variable scope is used to describe the availability of a variable to the code in your program. There are two main scopes ...
Where we learn about variable scope 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? 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. 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'.
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 '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. Now run the game and enjoy! 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. Download the worksheet 'Understanding hangman' and complete the activities. Hand the worksheet in to your teacher for checking. 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 ...
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.
Click to load key word list to help you make your own flash cards
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. |