SlideShare a Scribd company logo
1 of 6
Download to read offline
WEEK
FIVE
Writing your own functions
Well done for making it to the final week of the challenge!
This week we have got some really interesting questions lined up for you.
You have been calling functions for several weeks now, either builtin functions like raw_input, functions from
modules like random.shuffle, or methods like reverse for lists.
Now that your programs are becoming more complicated it is time for us to show you how to write your own
functions. This will allow you to make your programs simpler, and therefore easier to understand and debug.
1 Functions
A function is an independent, named chunk of code that performs a specific operation. It can be run or called
by referring to it by name with any information called arguments it needs to do its job. By now you will have
had lots of experience calling builtin functions like raw_input or int. Both raw_input and int take a single
argument. For raw_input this is the message to display to the user, e.g. ’Enter a number: ’, and for int
it is the value to be converted into an integer, e.g. ’10’.
Different languages (and textbooks) sometimes have different terms for functions. They may also be called
routines, subroutines, subprograms, procedures, messages or methods. Many languages differentiate procedures
from functions by saying that functions return a value but procedures don’t. Since languages like C/C++ and Java
have a void or empty return type (equivalent to None in Python) the distinction no longer makes sense.
Using functions in Python is easy — so easy that we have been using them without really bothering to properly
introduce function calls. On the whole, defining your own functions in Python is straightforward. However, there
are a number of tricks that can catch you out occasionally. We mention some of those things below.
The clever thing about functions is that the same bit of code can be called again and again, rather than having to
write it out multiple times. If we need to make a change to that code we only have to do it in one place rather than
each copy. Also, we can use functions to hide complicated code so we don’t have to think about it so carefully
when we use it.
2 Function Calls
You have already an old hand at calling functions, but let’s recap quickly to make sure you understand it all.
To call a function you need to how many arguments the function is expecting and what type of values they are.
For instance, the abs builtin function takes one argument which must be an integer, float (or complex number).
Hopefully, if the function’s purpose is well defined it will be obvious what information the function needs and
why. That is, unless you have a number, then it is meaningless to ask about its absolute value!
The examples below show what happens when you give abs the wrong number or type of arguments:
c National Computer Science School 2005-2009 1
NCSS Challenge (Beginners) WEEK FIVE
>>> abs(1, 3)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
abs(1, 3)
TypeError: abs() takes exactly one argument (2 given)
>>> abs()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
abs()
TypeError: abs() takes exactly one argument (0 given)
>>> abs(’a’)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in -toplevel-
abs(’a’)
TypeError: bad operand type for abs()
A function call consists of the function name, which may need to be preceded (or qualified by the module name,
followed by the arguments surrounded by parentheses. A common mistake is to forget to put the brackets when
the function takes no arguments.
>>> abs
<built-in function abs>
Unfortunately, abs without the parentheses is not an error since abs is a variable which holds the actual code
that performs the absolute value. Typing abs, is asking to see the contents of the variable, not call the function.
3 Creating your own functions
Functions in Python are created using a definition statement. The def creates a function from the indented
function body and assigns it to the name of the function.
>>> def hello(name):
... print ’Hello’, name
...
>>> hello(’James’)
Hello James
A definition statement consists of the keyword def, followed by the function name (here hello), and then a list
of zero or more arguments in parentheses (here just one, name). The parentheses must be present even when the
function takes no arguments. The def line must end with a colon (like control statements). The code block of
the function must be indented as in control statements.
The def statement is executed in the same order as other statements which means your program must reach the
def statement before it tries to call the function:
hello(’James’)
def hello(name):
print ’Hello’, name
When you run this, Python spits out the following error:
Traceback (most recent call last):
File ‘‘example.py’’, line 3, in ?
hello(’James’)
NameError: name ’hello’ is not defined
c National Computer Science School 2005-2009 2
NCSS Challenge (Beginners) WEEK FIVE
This is because Python attempts to run the call to hello before the function itself actually exists, which is why
the name hello is undefined.
Here is a function that performs factorial, that is, for a number n it calculates n x n - 1 x ... x 1, so 5 factorial,
written 5!, is 5 x 4 x 3 x 2 x 1 = 120. The Python version is:
>>> def fact(n):
... result = 1
... while n > 1:
... result *= n
... n = n - 1
... return result
...
>>>
Running this code with 3 calls to fact gives:
>>> print fact(5), fact(10), fact(20)
120 3628800 2432902008176640000
As you can see those factorial numbers get very large very quickly!
4 return Statements
As we have seen, some functions (such as fact above) need to give the result of their execution back to the
caller. This is done using a return statement.
>>> def add(x, y):
... return x + y
...
>>> r = add(5, 10)
>>> r
15
A return statement immediately terminates the running function and control is passed back to the caller, that
is, the line of code that called the function continues. If return is given an argument, then it is returned to the
caller and can be stored in a variable, used in an expression, or discarded.
If return is not given a value, then no value is returned to the caller (None is returned instead). This is the same
as a function which has finished executing and does not have a return statement. The hello function above is
an example without a return. Because a return statement terminates the execution immediately, it is often used to
exit from a function before the last line of code.
>>> def hi():
... print ’hello’
... return
... print ’there’
...
>>> hi()
hello
In this example, print ’there’ will never get called because the return statement, will cause the function to
exit before the second print is reached.
As in the above examples, when a function needs to return an argument, the return statement is followed by
a single expression which is evaluated and returned to the caller. A return statement can appear anywhere,
including inside if, for and while statements, in which case the function immediately returns.
c National Computer Science School 2005-2009 3
NCSS Challenge (Beginners) WEEK FIVE
>>> def day(name):
... if name in [’Saturday’, ’Sunday’]:
... return ’weekend’
... elif name in [’Monday’, ’Tuesday’, ’Wednesday’, ’Thursday’, ’Friday’]:
... return ’weekday’
... else:
... return ’not a day’
>>> day(’Monday’)
’weekday’
>>> day(’Sunday’)
’weekend’
In this function there are three separate return statements that correspond to the three different conditions that
this function handles.
5 Arguments
Communicating information to a function can occur in two ways: Either the function declares a number of
arguments (or parameters) which must be passed to it when the function is called, or the function uses variables
that are defined in the main program.
You have probably guessed from the examples above how arguments can be used because it’s kind of hard to
do interesting examples without them. That’s not surprising since arguments provide the information functions
need to do their work.
Adding arguments to a function is as simple as adding variable names between the parentheses in the def
statement. Then when the function is called, the value you want that argument to have in that call will need
to be added between the parentheses too. The names of the variables inside (the function definition) and outside
(in the function call) need not be the same. For this week’s problems it is relatively easy since our checking code
will tell you if you have defined your functions incorrectly.
Arguments are the trickiest part of creating functions because they don’t quite behave how you might expect. The
biggest surprise is that arguments (and variables) that are declared as part of a function are not visible outside
that function (in the main program or other functions):
>>> def hello(name):
... print ’Hello’, name
...
>>> hello(’James’)
Hello James
>>> name
Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
NameError: name ’name’ is not defined
Another complication is that you can’t change values that are passed into a function:
>>> def addone(x):
... x += 1
...
You might expect that if we call this function on a variable, say y, then the value of y would be incremented by
one after the function call:
>>> y = 5
>>> addone(y)
>>> y
5
>>>
c National Computer Science School 2005-2009 4
NCSS Challenge (Beginners) WEEK FIVE
Outside the function nothing has changed, but x inside the function would have been incremented by one. This is
because Python functions make a copy of their arguments (called pass by value) rather than access the original
variables.
So in the case above, a new local variable x has been creating containing a copy of the contents of the variable y
that was passed in as an argument during the function call. When we modify x inside the function we are only
modifying that local variable.
What this means is that if we want to modify a variable we need to pass it in to the function and then return it,
like this:
>>> def addone(x):
... return x + 1
...
>>> y = 5
>>> y = addone(5)
>>> y
6
>>>
There is one final complication with passing by value, and that is that Python data structures are stored as
references. We don’t want to go into the details of what that means now, but the gotcha is that they can be
modified (but not assigned) inside a function call:
>>> def appendone(x):
... x.append(1)
...
>>> y = []
>>> appendone(y)
>>> y
[1]
>>> appendone(y)
>>> y
[1, 1]
>>>
6 Testing functions in IDLE
In the examples above we have developed our functions in the Python shell rather than in a separate file IDLE.
However, you normally develop programs in separate Python files and then run them. So how do you do that for
your own functions?
Say you have just written your own function in a separate file in IDLE and you want to test it. For example:
def greet(name):
return ’Hello ’ + name
You can test this in the interactive interpreter in the same way by pressing F5 (or selecting Run Module from
the Run menu). But when you do this nothing seems to happen because you have no code apart from the def
statement in your file, and the def statement doesn’t produce any output on the Python shell:
>>> ================================ RESTART ================================
>>>
What you need to do then is call your function manually:
>>> greet(’James’)
’Hello James’
>>>
c National Computer Science School 2005-2009 5
NCSS Challenge (Beginners) WEEK FIVE
7 More dictionary methods
Sometimes you’ll need to either retrieve the value for a particular key from the dictionary, or use a default value
if the key doesn’t exist. This typically takes 3 lines of Python:
>>> val = ’default’
>>> if key in d:
... val = d[key]
>>>
However, getting a key-value pair or default is so common, dictionaries provide the get method to simplify this:
>>> val = d.get(key, ’default’)
The first argument to get is the key. If the key is in the dictionary then the corresponding value is returned,
otherwise the second argument to get (here ’default’) is returned.
If you want to copy the key-value pairs from one dictionary to another, Python provides the update method:
>>> d1 = {’a’: 1, ’b’: 5}
>>> d2 = {’a’: 4, ’c’: 6}
>>> d1.update(d2)
>>> d1
{’a’: 4, ’c’: 6, ’b’: 5}
Notice that not only does the new key ’c’ have the value 5 from d2, but the value for ’a’ has also been updated
to the value from d2.
8 Miscellaneous string tricks
To make a couple of the questions a bit easier, here are a last couple of miscellaneous tricks:
Firstly, the string module has some useful constants:
>>> import string
>>> string.lowercase
’abcdefghijklmnopqrstuvwxyz’
>>> string.punctuation
’!"#$%&’()*+,-./:;<=>?%%[]^_‘{|}~’
>>>
If you need to strip off all punctuation, you can now use:
>>> x = "’Hello!’"
>>> x.strip(string.punctuation)
’Hello’
>>>
c National Computer Science School 2005-2009 6

More Related Content

What's hot (20)

Function in c program
Function in c programFunction in c program
Function in c program
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function in c
Function in cFunction in c
Function in c
 
Functions1
Functions1Functions1
Functions1
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
Function in C program
Function in C programFunction in C program
Function in C program
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Function lecture
Function lectureFunction lecture
Function lecture
 
Functions
FunctionsFunctions
Functions
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Inline function
Inline functionInline function
Inline function
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
C function
C functionC function
C function
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
PHP 7
PHP 7PHP 7
PHP 7
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 

Viewers also liked

3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013hccit
 
Week05
Week05Week05
Week05hccit
 
Week04
Week04Week04
Week04hccit
 
Notes2
Notes2Notes2
Notes2hccit
 
Week03
Week03Week03
Week03hccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 

Viewers also liked (7)

3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
 
Week05
Week05Week05
Week05
 
Week04
Week04Week04
Week04
 
Notes2
Notes2Notes2
Notes2
 
Week03
Week03Week03
Week03
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 

Similar to Notes5

Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxleavatin
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdfpaijitk
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdfpaijitk
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxabhi353063
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxAaliyanShaikh
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structurecogaxor346
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuplesMalligaarjunanN
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 

Similar to Notes5 (20)

Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
ex 2.pdf
ex 2.pdfex 2.pdf
ex 2.pdf
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 

More from hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqhccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mjhccit
 

More from hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedq
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Notes5

  • 1. WEEK FIVE Writing your own functions Well done for making it to the final week of the challenge! This week we have got some really interesting questions lined up for you. You have been calling functions for several weeks now, either builtin functions like raw_input, functions from modules like random.shuffle, or methods like reverse for lists. Now that your programs are becoming more complicated it is time for us to show you how to write your own functions. This will allow you to make your programs simpler, and therefore easier to understand and debug. 1 Functions A function is an independent, named chunk of code that performs a specific operation. It can be run or called by referring to it by name with any information called arguments it needs to do its job. By now you will have had lots of experience calling builtin functions like raw_input or int. Both raw_input and int take a single argument. For raw_input this is the message to display to the user, e.g. ’Enter a number: ’, and for int it is the value to be converted into an integer, e.g. ’10’. Different languages (and textbooks) sometimes have different terms for functions. They may also be called routines, subroutines, subprograms, procedures, messages or methods. Many languages differentiate procedures from functions by saying that functions return a value but procedures don’t. Since languages like C/C++ and Java have a void or empty return type (equivalent to None in Python) the distinction no longer makes sense. Using functions in Python is easy — so easy that we have been using them without really bothering to properly introduce function calls. On the whole, defining your own functions in Python is straightforward. However, there are a number of tricks that can catch you out occasionally. We mention some of those things below. The clever thing about functions is that the same bit of code can be called again and again, rather than having to write it out multiple times. If we need to make a change to that code we only have to do it in one place rather than each copy. Also, we can use functions to hide complicated code so we don’t have to think about it so carefully when we use it. 2 Function Calls You have already an old hand at calling functions, but let’s recap quickly to make sure you understand it all. To call a function you need to how many arguments the function is expecting and what type of values they are. For instance, the abs builtin function takes one argument which must be an integer, float (or complex number). Hopefully, if the function’s purpose is well defined it will be obvious what information the function needs and why. That is, unless you have a number, then it is meaningless to ask about its absolute value! The examples below show what happens when you give abs the wrong number or type of arguments: c National Computer Science School 2005-2009 1
  • 2. NCSS Challenge (Beginners) WEEK FIVE >>> abs(1, 3) Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel- abs(1, 3) TypeError: abs() takes exactly one argument (2 given) >>> abs() Traceback (most recent call last): File "<pyshell#1>", line 1, in -toplevel- abs() TypeError: abs() takes exactly one argument (0 given) >>> abs(’a’) Traceback (most recent call last): File "<pyshell#2>", line 1, in -toplevel- abs(’a’) TypeError: bad operand type for abs() A function call consists of the function name, which may need to be preceded (or qualified by the module name, followed by the arguments surrounded by parentheses. A common mistake is to forget to put the brackets when the function takes no arguments. >>> abs <built-in function abs> Unfortunately, abs without the parentheses is not an error since abs is a variable which holds the actual code that performs the absolute value. Typing abs, is asking to see the contents of the variable, not call the function. 3 Creating your own functions Functions in Python are created using a definition statement. The def creates a function from the indented function body and assigns it to the name of the function. >>> def hello(name): ... print ’Hello’, name ... >>> hello(’James’) Hello James A definition statement consists of the keyword def, followed by the function name (here hello), and then a list of zero or more arguments in parentheses (here just one, name). The parentheses must be present even when the function takes no arguments. The def line must end with a colon (like control statements). The code block of the function must be indented as in control statements. The def statement is executed in the same order as other statements which means your program must reach the def statement before it tries to call the function: hello(’James’) def hello(name): print ’Hello’, name When you run this, Python spits out the following error: Traceback (most recent call last): File ‘‘example.py’’, line 3, in ? hello(’James’) NameError: name ’hello’ is not defined c National Computer Science School 2005-2009 2
  • 3. NCSS Challenge (Beginners) WEEK FIVE This is because Python attempts to run the call to hello before the function itself actually exists, which is why the name hello is undefined. Here is a function that performs factorial, that is, for a number n it calculates n x n - 1 x ... x 1, so 5 factorial, written 5!, is 5 x 4 x 3 x 2 x 1 = 120. The Python version is: >>> def fact(n): ... result = 1 ... while n > 1: ... result *= n ... n = n - 1 ... return result ... >>> Running this code with 3 calls to fact gives: >>> print fact(5), fact(10), fact(20) 120 3628800 2432902008176640000 As you can see those factorial numbers get very large very quickly! 4 return Statements As we have seen, some functions (such as fact above) need to give the result of their execution back to the caller. This is done using a return statement. >>> def add(x, y): ... return x + y ... >>> r = add(5, 10) >>> r 15 A return statement immediately terminates the running function and control is passed back to the caller, that is, the line of code that called the function continues. If return is given an argument, then it is returned to the caller and can be stored in a variable, used in an expression, or discarded. If return is not given a value, then no value is returned to the caller (None is returned instead). This is the same as a function which has finished executing and does not have a return statement. The hello function above is an example without a return. Because a return statement terminates the execution immediately, it is often used to exit from a function before the last line of code. >>> def hi(): ... print ’hello’ ... return ... print ’there’ ... >>> hi() hello In this example, print ’there’ will never get called because the return statement, will cause the function to exit before the second print is reached. As in the above examples, when a function needs to return an argument, the return statement is followed by a single expression which is evaluated and returned to the caller. A return statement can appear anywhere, including inside if, for and while statements, in which case the function immediately returns. c National Computer Science School 2005-2009 3
  • 4. NCSS Challenge (Beginners) WEEK FIVE >>> def day(name): ... if name in [’Saturday’, ’Sunday’]: ... return ’weekend’ ... elif name in [’Monday’, ’Tuesday’, ’Wednesday’, ’Thursday’, ’Friday’]: ... return ’weekday’ ... else: ... return ’not a day’ >>> day(’Monday’) ’weekday’ >>> day(’Sunday’) ’weekend’ In this function there are three separate return statements that correspond to the three different conditions that this function handles. 5 Arguments Communicating information to a function can occur in two ways: Either the function declares a number of arguments (or parameters) which must be passed to it when the function is called, or the function uses variables that are defined in the main program. You have probably guessed from the examples above how arguments can be used because it’s kind of hard to do interesting examples without them. That’s not surprising since arguments provide the information functions need to do their work. Adding arguments to a function is as simple as adding variable names between the parentheses in the def statement. Then when the function is called, the value you want that argument to have in that call will need to be added between the parentheses too. The names of the variables inside (the function definition) and outside (in the function call) need not be the same. For this week’s problems it is relatively easy since our checking code will tell you if you have defined your functions incorrectly. Arguments are the trickiest part of creating functions because they don’t quite behave how you might expect. The biggest surprise is that arguments (and variables) that are declared as part of a function are not visible outside that function (in the main program or other functions): >>> def hello(name): ... print ’Hello’, name ... >>> hello(’James’) Hello James >>> name Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel- NameError: name ’name’ is not defined Another complication is that you can’t change values that are passed into a function: >>> def addone(x): ... x += 1 ... You might expect that if we call this function on a variable, say y, then the value of y would be incremented by one after the function call: >>> y = 5 >>> addone(y) >>> y 5 >>> c National Computer Science School 2005-2009 4
  • 5. NCSS Challenge (Beginners) WEEK FIVE Outside the function nothing has changed, but x inside the function would have been incremented by one. This is because Python functions make a copy of their arguments (called pass by value) rather than access the original variables. So in the case above, a new local variable x has been creating containing a copy of the contents of the variable y that was passed in as an argument during the function call. When we modify x inside the function we are only modifying that local variable. What this means is that if we want to modify a variable we need to pass it in to the function and then return it, like this: >>> def addone(x): ... return x + 1 ... >>> y = 5 >>> y = addone(5) >>> y 6 >>> There is one final complication with passing by value, and that is that Python data structures are stored as references. We don’t want to go into the details of what that means now, but the gotcha is that they can be modified (but not assigned) inside a function call: >>> def appendone(x): ... x.append(1) ... >>> y = [] >>> appendone(y) >>> y [1] >>> appendone(y) >>> y [1, 1] >>> 6 Testing functions in IDLE In the examples above we have developed our functions in the Python shell rather than in a separate file IDLE. However, you normally develop programs in separate Python files and then run them. So how do you do that for your own functions? Say you have just written your own function in a separate file in IDLE and you want to test it. For example: def greet(name): return ’Hello ’ + name You can test this in the interactive interpreter in the same way by pressing F5 (or selecting Run Module from the Run menu). But when you do this nothing seems to happen because you have no code apart from the def statement in your file, and the def statement doesn’t produce any output on the Python shell: >>> ================================ RESTART ================================ >>> What you need to do then is call your function manually: >>> greet(’James’) ’Hello James’ >>> c National Computer Science School 2005-2009 5
  • 6. NCSS Challenge (Beginners) WEEK FIVE 7 More dictionary methods Sometimes you’ll need to either retrieve the value for a particular key from the dictionary, or use a default value if the key doesn’t exist. This typically takes 3 lines of Python: >>> val = ’default’ >>> if key in d: ... val = d[key] >>> However, getting a key-value pair or default is so common, dictionaries provide the get method to simplify this: >>> val = d.get(key, ’default’) The first argument to get is the key. If the key is in the dictionary then the corresponding value is returned, otherwise the second argument to get (here ’default’) is returned. If you want to copy the key-value pairs from one dictionary to another, Python provides the update method: >>> d1 = {’a’: 1, ’b’: 5} >>> d2 = {’a’: 4, ’c’: 6} >>> d1.update(d2) >>> d1 {’a’: 4, ’c’: 6, ’b’: 5} Notice that not only does the new key ’c’ have the value 5 from d2, but the value for ’a’ has also been updated to the value from d2. 8 Miscellaneous string tricks To make a couple of the questions a bit easier, here are a last couple of miscellaneous tricks: Firstly, the string module has some useful constants: >>> import string >>> string.lowercase ’abcdefghijklmnopqrstuvwxyz’ >>> string.punctuation ’!"#$%&’()*+,-./:;<=>?%%[]^_‘{|}~’ >>> If you need to strip off all punctuation, you can now use: >>> x = "’Hello!’" >>> x.strip(string.punctuation) ’Hello’ >>> c National Computer Science School 2005-2009 6