Sie sind auf Seite 1von 32

Mastering Programming in Python

Lesson 6

Functions, parameters and local/global variables

The full series and 100s of other resources are available from

Series Overview

Introduction to the language, SEQUENCE variables, create a Chat bot

SELECTION (if else statements)
ITERATION (While loops)
Introducing For Loops
Challenges and tasks for Mastering Iteration
Use of Functions/Modular Programming
Introducing Lists /Operations/List comprehension
Tuples, sets, lists, dictionaries
Use of Dictionaries
Doing things with strings
File Handling Reading, writing, appending text files
Working with CSV files
Practical Programming (plenty of engaging scenarios, challenges
and tasks to get you thinking)
Consolidation of all your skills useful resources
Includes Computer Science theory and Exciting themes for every
lesson including: Quantum Computing, History of Computing,
Future of storage, Brain Processing, Systems life Cycle, Testing
and more

Task (Code provided)
Challenge (DIY!)
Suggested Project/HW

*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)

In this lesson you will

Learn about Functions in Python

The use (advantages) of using Functions
Robotics what do you know?
Introduction to Modular Design
Local and Global Variables
Passing parameters & What are arguments?
Built in Functions (Python 3)
Big Questions: Evolution vs Intelligent Design in
light of functions (modular design)
Challenges, including Q and A (with solutions)
Suggested Research/HW and Youtube Videos

*For this series we

assume students
know how to open,
save and run a
python module.
Version: Python 3


I, Robot a book by Isaac


Robotics is a branch of mechanical engineering and

computer science and it deals with the design, creation
and application of robots.
You may have watched I, ROBOT and considered the
impact that robots will have on society in the future.
Imagine a world in which robots brought us tea and ran
errands for us! I, ROBOT was based on a popular book.
The author Isaac Asimov wrote science fiction and was
famous for his Three Laws of Robotics. He imagined
things way back then that are now a reality!
If youre interested in this field, you may want to check out the WIKIPEDIA page on the
topic and look at the timeline of robotics through the ages. Where will it all lead?!

Introducing the concept of Modular Design

Modular design, or "modularity in design", is a design
approach that subdivides a system into smaller parts
called modules. These modules can be independently
created and then used in different systems. A modular
system can be characterized by functional partitioning
into discrete scalable, reusable modules.
Imagine a company with one hundred robotics specialists that was planning to build a
robot. It wouldnt make much sense for all one hundred people to work on the arm,
and then the leg and then the eye.
Instead groups could be formed and each group (team) could work on a specific
module. Advantages: The module for each body part could then potentially be re-used
in future robots as well! This would save both time and money in development and
testing. Each module would however, have to be integrated into the whole system.

More on Modular Design

Modular programming is basically a design technique to
split your code into separate parts or modules. One of
the goals of this separation should be to have modules
with no or just few dependencies upon other modules.

Modular design helps produce

programs that are:



Easy to test

Or to put it another way: Minimization of dependencies is

the goal.
The executable application will be created by putting
them together.
When creating a modular system, several modules are
built separately and more or less independently.
Modules can contain functions, but there are statements in them as well. Statements
are typically used to initiate the module, only executed when the module is imported.

What are functions?

A function is a block of organized and
generally reusable code that is used to
perform a single, related action. A function
typically returns a single value (like a
number, or true or false. Functions
provide a better platform for modularity
and a high degree of code reusing.

functionname( parameters ):
return [expression]

Syntax of a Function in Python

Python has a number of built in functions (like Print(), but we can also
code our own functions and these are called user defined functions.
By default, parameters have a positional behaviour and you need to
inform them in the same order that they were defined.

All you need to know about Functions

A Function block will start with the keyword def followed by the function name
and parentheses ( ( ) ). A function (unlike a procedure) returns a single value.
Input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function. It can pass back an
expression to the caller. A return statement with no arguments is the same as
return None.

The anatomy of a function

def function_name(parameter_1,parameter_2):
{this bit is your code which is in the function}
{more code}
{and still more code}
return {value to return to the main program}
{now, this bit of code is NOT in the function}
{Why? because it isn't indented}
#dont forget to put a colon ":" at the end
#... of the line that starts with 'def'

Task: Lets start with something cool!

If you are working with a computer
that already has Python and Pygame
set up on it, you can skip this step.
But if you want to set up Python and
Pygame on your own Windows
computer, don't worry. It is very easy.
Run the Python installer downloaded
Run the Pygame installer
downloaded from:

*Read more about Pygame here:

Download Pygame (see left for instructions)

Copy the code in the speaker notes

Run the program and play!

*On the next slide, well point out the function!

Task: Lets start with something cool!

Question 1: Can you spot the function?

Question 2: What parameters are being passed to
the function?
Question 3: What are those bizarre numbers
being printed to the screen!?
*Answers in speakernotes below

Video demonstration

And now, lets really get into coding Functions: (Example: create a function and passing parameters)

Example of the use of a Function #1

First, type this
in. Note you
have a function
and you need to
pass a string
parameter into
Next, press F5
to run the code.
Type in
boo). The
boo (which is
a string) is
passed to the
function and

Example of the use of a Function #2

Once you have

the basic
structure of a
function, you
can execute it
by calling it
from another
function or
directly from
the prompt.

In this example
we are calling
function twice
(and passing it
different string
each time)

Parameters / Arguments
Passing parameters by reference or passing parameters by value
All parameters
(arguments) in
the Python
language are
passed by
reference. It
means if you
change what a
parameter refers
to within a
function, the
change also
reflects back in

#Example of passing parameters

def values_change ( mylist ):
"This changes a passed list into this
print "Values inside the function: ",

Here, we are
reference of the
passed object and
appending values in
the same object. So,
this would produce
the following result

# Now you can call values_change

mylist = [10,20,30];
the function:
[10, 20, 30,
[1, 2,
3, 4]]outside the function: ",
Values outside the function: [10, 20, 30,

[1, 2, 3, 4]]

Passing multiple parameters to a function

which requires
the input (on
calling the
function) of two

Here we are
calling the
function with
two parameters.
These are then

Arguments .
In essence, the words parameter and argument are used interchangeably.
You can call a function by using the following types of formal arguments:

# Function sum

We wont get in
to these in
detail in this
lesson, but feel
free to look
them up!

def sum( arg1, arg2 ):

# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

Understanding: Local and Global Variables

Imagine a big school building. Reception has a big computer screen in it, and
there are individual offices and classrooms with computer screens too.
Reception Computer Screen
Good morning

Headmasters office private email

Today I am
Going to expel
Joe Bloggs

Head of History teachers computer screen

Test scores:
Tom = A*
Jane = F
Hal = B

Understanding: Local and Global Variables

Only people in
the heads office
can see this
crazy message!
Its like a local
variable! Only
inside the
function its
declared in.
Headmasters office private email

Today I am
Going to expel
Joe Bloggs

Only those in this

classroom would
be able to see
Reception Computer Screen
these scores.
The scope of a
Good morning
determines the
portion of the
program where
you can access a
This message is Head of History teachers computer screen
available for
Test scores:
the school to
Tom = A*
see. It is like a
Jane = F
GLOBAL variable
Hal = B
(accessible to
the whole

Task: Local and Global variables

These are variables with GLOBAL scope

Num3 is only declared inside the test1 function

So it is a variable with LOCAL scope.

Analyse the
following code
carefully and see if
you can predict
the output when
both functions are
What will TEST1()
What about
*Answers on the next slide


Num3 is not a
GLOBAL variable
so cannot be
accessed by the
function test2. It
results in an error!

See if you can fill in the blanks

#This is a comment

total = 0; #This is a
# sum is the name of a function
def sum( arg1, arg2 ):
# Add both the parameters
and return them."
? variable.
total = arg1 + arg2; # Here, total is a local
print ("Inside the function local total : ", total)
return total; Note: It is also possible to store the output of a

function in a variable. To do so, we use the

keyword return.
are calling the sum function with two
? parameters.

# Here we
sum( 10, 20 );
print ("Outside the function global total : ", total)
#the output will be Global total = 0? and Local total = 30

Run the code and

try it for yourself.
Note how the
GLOBAL variable
is accessible by
the whole
The local variable
is only accessible
inside the
function it is
declared in.

Challenge 1:
Discuss and answer the following questions. Be prepared to share!
1. Analyse the code on the left. What does this
program do? Be specific and mention example
inputs and outputs.
Your answer here

2. Describe, using specialist terminology, what is

happening where the blue square is placed. What
is happening to variables w and h?
Your answer here

Challenge 2: Answer the following questions

1. Name all the functions in the program.
Your answer here

2. Name all the numeric parameters

Your answer here

3. Name any parameters that require string input.

Your answer here

4. Name any variables.

Your answer here

5. If the input is: Moose, 3, 10 whats the output?

Your answer here

Watch the following video demo:

Challenge coming up on the following slide! This demo shows a
little a program that prints a menu and converts from Celsius to
Fahrenheit (code below)

Note the use of

functions for the
menu and one
function for each

Challenge 3: The Ultimate converter!

On the previous slide you analysed the code that uses functions
to print a menu and convert, depending on user selection. Ready
for your challenge? Read on
# This is a little program that converts temperature to Fahrenheit or Celsius

1. Use the code in the previous slide (copy

and paste from the right although it is
preferred you type it out yourself)
2. Run it to see what it does.
3. Add a menu option and corresponding
function for
a) converting pounds to kilograms (youll
have to research this) and
b) converting into Euro (or any other

def print_options():
print("Make a selection:")
print(" 'p' Print this menu again")
print(" 'c' Convert from Celsius")
print(" 'f' convert from Fahrenheit")
print(" 'q' Exit this program")
def celsius_to_fahrenheit(c_temp):
return 9.0 / 5.0 * c_temp + 32
def fahrenheit_to_celsius(f_temp):
return (f_temp - 32.0) * 5.0 / 9.0
choice = "p"
while choice != "q":
if choice == "c":
c_temp = float(input("Celsius temperature: "))
print("Fahrenheit:", celsius_to_fahrenheit(c_temp))
choice = input("option: ")
elif choice == "f":
f_temp = float(input("Fahrenheit temperature: "))
print("Celsius:", fahrenheit_to_celsius(f_temp))
choice = input("option: ")
choice = "p" #Alternatively choice != "q": so that print
#when anything unexpected inputed
choice = input("option: ")

Challenge 4: Spot and change the mistake!

The following code (once you fix it) will create a simple but nifty

Solution in Speaker Notes (teachers delete before giving to student

# Program make a simple calculator that can add, subtract, multiply and divide using functions

1. Analyse the code on the right you can

cut and paste it into Python to look at it
more closely. It doesnt work can you
figure out why?
2. Hint: the word function in the code needs
to be replaced. What do you need to
replace it with?
3. Can you add any additional functionality
to this calculator things like square root
and MOD? Research MOD if you dont
know what it is itll come in handy when
youre programming!

# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))

Python has built in functions

Remember, at any
given time you can
always look up the
official python
documentation website
which will give you a
wealth of information.
Python also has a
range of built in

The Big Questions:
Do you think the fact that we see re-used
code and modules in DNA points to
Intelligent design? Why or why not?
Read the quote from author Bill Haines
(below) and discuss. What do you think?
Darwin's time was not only before the advent of computers and computer programming but also before the
discovery of the electron itself. We now know that everything is not the result of natural causes, with the
proliferation of computer programming and apps being a good example and that the genome, is the DNA software
of life- with many reusable code objects (genes) accepting many different design parameters (e.g.. short beaks /
long beaks.)

Useful Videos to watch on covered topics

Advances in Robotics advanced robots.

Recommended video on Python: Functions

Suggested Project / HW / Research

1. Create a research information point on the types of software development.
Research and include information on the following three.
Modular Design
Rapid Application development
Waterfall Method
2. Write an essay (or create an informational power point) on one of the following:
Recent developments in Robotics (what countries are at the forefront and where
will we be in 5 years?)
A history of robotics where did it all start, and where are we now?
The creation of a robot. What is involved? Give examples of robots that have been
created and are currently in use.
Extension task: What is MOD (Modulus). How does it work and can you find
examples of how it is used in programming or game design?

Useful links and additional reading