SlideShare a Scribd company logo
www.teachingcomputing.com
Mastering Programming in Python
Lesson 4
Functions, parameters and local/global variables
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
• Introduction to the language, SEQUENCE variables, create a Chat bot
• Introduction SELECTION (if else statements)
• Introducing ITERATION (While loops)
• Introducing For Loops
• Use of Functions/Modular Programming
• Introducing Lists /Operations/List comprehension
• Use of Dictionaries
• String Manipulation
• File Handling – Reading and writing to CSV Files
• Importing and Exporting Files
• Transversing, Enumeration, Zip Merging
• Recursion
• Practical Programming
• 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, and more …
Series Overview
*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)
Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Suggested Project/HW
Robotics
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!
I, Robot – a book by Isaac Asimov
If you’re 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
Imagine a company with one hundred robotics specialists that was planning to build a
robot. It wouldn’t make much sense for all one hundred people to work on the arm,
and then the leg and then the eye.
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.
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.
Or to put it another way: Minimization of dependencies is
the goal.
When creating a modular system, several modules are
built separately and more or less independently.
The executable application will be created by putting
them together.
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.
readable reliable
maintainable Easy to test
Modular design helps produce
programs that are:
What are functions?
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.
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.
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Syntax of a Function in Python
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}
#don’t forget to put a colon ":" at the end …
#... of the line that starts with 'def'
Video demonstration
(function and passing parameters)
Example of the use of a Function #1
First, type this in. Note
you have a function
called “functionprint”
and you need to pass
a string parameter
into it.
Next, press F5 to run
the code. Type in
“functionprint(“boo”).
The parameter “boo”
(which is a string) is
passed to the function
and printed!
Example of the use of a Function #2
In this example we are
calling the
functionprint function
twice (and passing it
different string
parameters each time)
Once you have the
basic structure of a
function, you can
execute it by calling it
from another function
or directly from the
prompt.
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 the calling
function. For example
−
#Example of passing parameters
def values_change ( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call values_change function
mylist = [10,20,30];
values_change( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining
reference of the passed
object and appending
values in the same
object. So, this would
produce the following
result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Passing multiple parameters to a function
Function “printdetails”
which requires the
input (on calling the
function) of two
parameters.
Here we are calling
the function with two
parameters. These are
then printed.
Arguments ….
# Function ‘sum’
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
In essence, the words ‘parameter’ and ‘argument’ are used interchangeably.
You can call a function by using the following types of formal arguments:
required
keyword
default
variable
We won’t get in to
these in detail in this
lesson, but feel free to
look them up!
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.
Good morning
Employees!
Reception Computer Screen
“Today I am
Going to expel
Joe Bloggs”
Headmasters office – private email
Test scores:
Tom = A*
Jane = F
Hal = B
Head of History – teacher’s computer screen
Understanding: Local and Global Variables
Good morning
Employees!
Reception Computer Screen
“Today I am
Going to expel
Joe Bloggs”
Headmasters office – private email
Test scores:
Tom = A*
Jane = F
Hal = B
Head of History – teacher’s computer screen
This message is
available for
EVERYONE in the
school to see. It is like
a GLOBAL variable
(accessible to the
whole program)
Only people in the
head’s office can see
this crazy message! It’s
like a local variable!
Only accessible inside
the function it’s
declared in.
Only those in this
classroom would be able
to ‘see’ these scores.
The scope of a variable
determines the portion of
the program where you
can access a particular
identifier
*Answers on the next slide
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 called.
What will TEST1() output?
What about TEST2()?
Task: Local and Global variables
Num3 is not a GLOBAL
variable so cannot be
accessed by the function
test2. It results in an
error!
Answers:
See if you can fill in the blanks …
#This is a comment
total = 0; #This is a global variable.
# ‘sum’ is the name of a function
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here, total is a local variable.
print ("Inside the function local total : ", total)
return total;
# Here we are calling the sum function with two parameters.
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 program.
The local variable is only
accessible inside the
function it is declared in.
Note: It is also possible to store the output of a function in a
variable. To do so, we use the keyword return.
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.
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
Your answer here
Challenge 2: Answer the following questions
1. Name all the functions in the program.
2. Name all the numeric parameters
3. Name any parameters that require string input.
4. Name any variables.
5. If the input is: “Moose”, 3, 10 – what’s the output?
Your answer here
Your answer here
Your answer here
Your answer here
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 conversion.
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…
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
(you’ll have to research this) and
b) converting £ into Euro (or any other
currency)
# This is a little program that converts temperature to Fahrenheit or Celsius
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: ")
else:
choice = "p" #Alternatively choice != "q": so that print
#when anything unexpected inputed
print_options()
choice = input("option: ")
Challenge 4: Spot and change the mistake!
The following code (once you fix it) will create a simple but nifty calculator!
1. Analyse the code on the right – you can
cut and paste it into Python to look at it
more closely. It doesn’t 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 don’t
know what it is – it’ll come in handy when
you’re programming!
# Program make a simple calculator that can add, subtract, multiply and divide using functions
# 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.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
Solution in Speaker Notes (teachers – delete before giving to students!)
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
functions:
https://docs.python.org/
3.2/library/functions.ht
ml
Discussion:
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
https://youtu.be/37VwgGRRt5g https://youtu.be/CGRKqnoQGgM
Advances in Robotics – advanced robots. Recommended video on Python: Functions
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?
Suggested Project / HW / Research
Useful links and additional reading
https://docs.python.org/3/tutorial/interpreter.html#argument-passing
https://en.wikipedia.org/wiki/Robot
http://www.afterhoursprogramming.com/tutorial/Python/Functions/
https://en.wikibooks.org/wiki/Python_Programming/Functions
https://youtu.be/CGRKqnoQGgM

More Related Content

What's hot (20)

PDF
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Niraj Bharambe
 
PDF
Basic Concepts in Python
Sumit Satam
 
PPT
Python Programming Language
Dr.YNM
 
PPTX
Intro to Python Programming Language
Dipankar Achinta
 
DOCX
PYTHON NOTES
Ni
 
PDF
Python made easy
Abhishek kumar
 
PPT
Python - Introduction
stn_tkiller
 
PDF
Python-01| Fundamentals
Mohd Sajjad
 
PPTX
Python Tutorial Part 1
Haitham El-Ghareeb
 
PDF
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
PDF
Python Workshop
Saket Choudhary
 
PDF
Python Tutorial
AkramWaseem
 
PPTX
Python introduction towards data science
deepak teja
 
PPTX
Python 3 Programming Language
Tahani Al-Manie
 
PPTX
Python second ppt
RaginiJain21
 
PPTX
Python Seminar PPT
Shivam Gupta
 
PPTX
The Awesome Python Class Part-3
Binay Kumar Ray
 
PPSX
Programming with Python
Rasan Samarasinghe
 
DOCX
Python interview questions
Pragati Singh
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Niraj Bharambe
 
Basic Concepts in Python
Sumit Satam
 
Python Programming Language
Dr.YNM
 
Intro to Python Programming Language
Dipankar Achinta
 
PYTHON NOTES
Ni
 
Python made easy
Abhishek kumar
 
Python - Introduction
stn_tkiller
 
Python-01| Fundamentals
Mohd Sajjad
 
Python Tutorial Part 1
Haitham El-Ghareeb
 
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Python Workshop
Saket Choudhary
 
Python Tutorial
AkramWaseem
 
Python introduction towards data science
deepak teja
 
Python 3 Programming Language
Tahani Al-Manie
 
Python second ppt
RaginiJain21
 
Python Seminar PPT
Shivam Gupta
 
The Awesome Python Class Part-3
Binay Kumar Ray
 
Programming with Python
Rasan Samarasinghe
 
Python interview questions
Pragati Singh
 

Similar to Mastering Python lesson 4_functions_parameters_arguments (20)

PPTX
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
PDF
Functions2.pdf
prasnt1
 
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
PPTX
2 Functions2.pptx
RohitYadav830391
 
PDF
Python_Functions.pdf
MikialeTesfamariam
 
PPTX
Python Functions.pptx
AnuragBharti27
 
PPTX
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
PDF
3-Python Functions.pdf in simple.........
mxdsnaps
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
PDF
Function
GauravGautam224100
 
PPTX
Functions2.pptx
AkhilTyagi42
 
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PPTX
UNIT 3 python.pptx
TKSanthoshRao
 
PDF
functions- best.pdf
MikialeTesfamariam
 
PDF
Functions_19_20.pdf
paijitk
 
PPT
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
PDF
Functions2.pdf
Daddy84
 
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions2.pdf
prasnt1
 
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
2 Functions2.pptx
RohitYadav830391
 
Python_Functions.pdf
MikialeTesfamariam
 
Python Functions.pptx
AnuragBharti27
 
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
3-Python Functions.pdf in simple.........
mxdsnaps
 
Python functions
Prof. Dr. K. Adisesha
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Functions2.pptx
AkhilTyagi42
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
UNIT 3 python.pptx
TKSanthoshRao
 
functions- best.pdf
MikialeTesfamariam
 
Functions_19_20.pdf
paijitk
 
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions2.pdf
Daddy84
 
Ad

Recently uploaded (20)

PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
epi editorial commitee meeting presentation
MIPLM
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Difference between write and update in odoo 18
Celine George
 
infertility, types,causes, impact, and management
Ritu480198
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Horarios de distribución de agua en julio
pegazohn1978
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Ad

Mastering Python lesson 4_functions_parameters_arguments

  • 1. www.teachingcomputing.com Mastering Programming in Python Lesson 4 Functions, parameters and local/global variables
  • 2. 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
  • 3. • Introduction to the language, SEQUENCE variables, create a Chat bot • Introduction SELECTION (if else statements) • Introducing ITERATION (While loops) • Introducing For Loops • Use of Functions/Modular Programming • Introducing Lists /Operations/List comprehension • Use of Dictionaries • String Manipulation • File Handling – Reading and writing to CSV Files • Importing and Exporting Files • Transversing, Enumeration, Zip Merging • Recursion • Practical Programming • 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, and more … Series Overview *Please note that each lesson is not bound to a specific time (so it can be taken at your own pace) Information/Theory/Discuss Task (Code provided) Challenge (DIY!) Suggested Project/HW
  • 4. Robotics 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! I, Robot – a book by Isaac Asimov If you’re 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?!
  • 5. Introducing the concept of Modular Design Imagine a company with one hundred robotics specialists that was planning to build a robot. It wouldn’t make much sense for all one hundred people to work on the arm, and then the leg and then the eye. 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. 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.
  • 6. 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. Or to put it another way: Minimization of dependencies is the goal. When creating a modular system, several modules are built separately and more or less independently. The executable application will be created by putting them together. 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. readable reliable maintainable Easy to test Modular design helps produce programs that are:
  • 7. What are functions? 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. 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. def functionname( parameters ): "function_docstring" function_suite return [expression] Syntax of a Function in Python By default, parameters have a positional behaviour and you need to inform them in the same order that they were defined.
  • 8. 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”.
  • 9. 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} #don’t forget to put a colon ":" at the end … #... of the line that starts with 'def'
  • 10. Video demonstration (function and passing parameters)
  • 11. Example of the use of a Function #1 First, type this in. Note you have a function called “functionprint” and you need to pass a string parameter into it. Next, press F5 to run the code. Type in “functionprint(“boo”). The parameter “boo” (which is a string) is passed to the function and printed!
  • 12. Example of the use of a Function #2 In this example we are calling the functionprint function twice (and passing it different string parameters each time) Once you have the basic structure of a function, you can execute it by calling it from another function or directly from the prompt.
  • 13. 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 the calling function. For example − #Example of passing parameters def values_change ( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call values_change function mylist = [10,20,30]; values_change( mylist ); print "Values outside the function: ", mylist Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result − Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
  • 14. Passing multiple parameters to a function Function “printdetails” which requires the input (on calling the function) of two parameters. Here we are calling the function with two parameters. These are then printed.
  • 15. Arguments …. # Function ‘sum’ def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; In essence, the words ‘parameter’ and ‘argument’ are used interchangeably. You can call a function by using the following types of formal arguments: required keyword default variable We won’t get in to these in detail in this lesson, but feel free to look them up!
  • 16. 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. Good morning Employees! Reception Computer Screen “Today I am Going to expel Joe Bloggs” Headmasters office – private email Test scores: Tom = A* Jane = F Hal = B Head of History – teacher’s computer screen
  • 17. Understanding: Local and Global Variables Good morning Employees! Reception Computer Screen “Today I am Going to expel Joe Bloggs” Headmasters office – private email Test scores: Tom = A* Jane = F Hal = B Head of History – teacher’s computer screen This message is available for EVERYONE in the school to see. It is like a GLOBAL variable (accessible to the whole program) Only people in the head’s office can see this crazy message! It’s like a local variable! Only accessible inside the function it’s declared in. Only those in this classroom would be able to ‘see’ these scores. The scope of a variable determines the portion of the program where you can access a particular identifier
  • 18. *Answers on the next slide 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 called. What will TEST1() output? What about TEST2()? Task: Local and Global variables
  • 19. Num3 is not a GLOBAL variable so cannot be accessed by the function test2. It results in an error! Answers:
  • 20. See if you can fill in the blanks … #This is a comment total = 0; #This is a global variable. # ‘sum’ is the name of a function def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here, total is a local variable. print ("Inside the function local total : ", total) return total; # Here we are calling the sum function with two parameters. 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 program. The local variable is only accessible inside the function it is declared in. Note: It is also possible to store the output of a function in a variable. To do so, we use the keyword return.
  • 21. 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. 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 Your answer here
  • 22. Challenge 2: Answer the following questions 1. Name all the functions in the program. 2. Name all the numeric parameters 3. Name any parameters that require string input. 4. Name any variables. 5. If the input is: “Moose”, 3, 10 – what’s the output? Your answer here Your answer here Your answer here Your answer here Your answer here
  • 23. 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 conversion.
  • 24. 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… 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 (you’ll have to research this) and b) converting £ into Euro (or any other currency) # This is a little program that converts temperature to Fahrenheit or Celsius 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: ") else: choice = "p" #Alternatively choice != "q": so that print #when anything unexpected inputed print_options() choice = input("option: ")
  • 25. Challenge 4: Spot and change the mistake! The following code (once you fix it) will create a simple but nifty calculator! 1. Analyse the code on the right – you can cut and paste it into Python to look at it more closely. It doesn’t 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 don’t know what it is – it’ll come in handy when you’re programming! # Program make a simple calculator that can add, subtract, multiply and divide using functions # 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.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) Solution in Speaker Notes (teachers – delete before giving to students!)
  • 26. 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 functions: https://docs.python.org/ 3.2/library/functions.ht ml
  • 27. Discussion: 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.) “
  • 28. Useful Videos to watch on covered topics https://youtu.be/37VwgGRRt5g https://youtu.be/CGRKqnoQGgM Advances in Robotics – advanced robots. Recommended video on Python: Functions
  • 29. 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? Suggested Project / HW / Research
  • 30. Useful links and additional reading https://docs.python.org/3/tutorial/interpreter.html#argument-passing https://en.wikipedia.org/wiki/Robot http://www.afterhoursprogramming.com/tutorial/Python/Functions/ https://en.wikibooks.org/wiki/Python_Programming/Functions https://youtu.be/CGRKqnoQGgM

Editor's Notes

  • #2: Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  • #3: Image source: http://www.peardeck.com
  • #4: Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  • #5: Image(s) source: Wikipedia
  • #6: Image(s) source: Wikipedia
  • #7: Image(s) source: http://www.desy.de/gna/html/cc/Tutorial/img4.gif
  • #23: #This is a program that ... def hello(): print('Hello!') def area(width, height): return width * height def print_welcome(name): print('Welcome,', name) def positive_input(prompt): number = float(input(prompt)) while number <= 0: print('Must be a positive number') number = float(input(prompt)) return number name = input('Your Name: ') hello() print_welcome(name) print() print('To find the area of a rectangle,') print('enter the width and height below.') print() w = positive_input('Width: ') h = positive_input('Height: ') print('Width =', w, ' Height =', h, ' so Area =', area(w, h))
  • #24: # This is a little program that converts temperature to Fahrenheit or Celsius 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: ") else: choice = "p" #Alternatively choice != "q": so that print #when anything unexpected inputed print_options() choice = input("option: ")
  • #26: Solution: If you didn’t see it yourself - ‘Function needs to be replaced by the actual function names – like add/subtract/divide etc.’ # Program make a simple calculator that can add, subtract, multiply and divide using functions # 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.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input")
  • #28: Image source: https://mrbarlow.files.wordpress.com/2012/10/dna-code.png
  • #30: Image(s) source: Wikipedia
  • #31: Image(s) source: Wikipedia