SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (19)

Function in c program
Function in c programFunction in c program
Function in c program
CGC Technical campus,Mohali
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
eShikshak
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
Allan Marques Baptista
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Function in c
Function in cFunction in c
Function in c
Raj Tandukar
 
Functions1
Functions1Functions1
Functions1
DrUjwala1
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
Michael Heron
 
Function in C program
Function in C programFunction in C program
Function in C program
Nurul Zakiah Zamri Tan
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
Subhasis Nayak
 
Function lecture
Function lectureFunction lecture
Function lecture
DIT University, Dehradun
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
C function
C functionC function
C function
thirumalaikumar3
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
Deepak Singh
 
PHP 7
PHP 7PHP 7
PHP 7
Joshua Copeland
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
Connex
 

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
hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
hccit
 
Week05
Week05Week05
Week05
hccit
 
Week04
Week04Week04
Week04
hccit
 
Notes2
Notes2Notes2
Notes2
hccit
 
Week03
Week03Week03
Week03
hccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
hccit
 
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
hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
hccit
 
Week05
Week05Week05
Week05
hccit
 
Week04
Week04Week04
Week04
hccit
 
Notes2
Notes2Notes2
Notes2
hccit
 
Week03
Week03Week03
Week03
hccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
hccit
 
Ad

Similar to Notes5 (20)

Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
ex 2.pdf
ex 2.pdfex 2.pdf
ex 2.pdf
SridharCS7
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptxJNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
Mohammad Hassan
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
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
abhi353063
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
KavithaChekuri3
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
ethiouniverse
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
function ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptxfunction ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptx
trwdcn
 
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
KrithikaTM
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
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
abhi353063
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
 
function ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptxfunction ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptx
trwdcn
 
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
KrithikaTM
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
Ad

More from hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
hccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
hccit
 
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
hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
hccit
 
Photoshop
PhotoshopPhotoshop
Photoshop
hccit
 
Flash
FlashFlash
Flash
hccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
hccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
hccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
hccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
hccit
 
Movies questions
Movies questionsMovies questions
Movies questions
hccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
hccit
 
Section b
Section bSection b
Section b
hccit
 
B
BB
B
hccit
 
A
AA
A
hccit
 
Section a
Section aSection a
Section a
hccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
hccit
 
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
hccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
hccit
 
Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
hccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
hccit
 
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
hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
hccit
 
Photoshop
PhotoshopPhotoshop
Photoshop
hccit
 
Flash
FlashFlash
Flash
hccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
hccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
hccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
hccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
hccit
 
Movies questions
Movies questionsMovies questions
Movies questions
hccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
hccit
 
Section b
Section bSection b
Section b
hccit
 
Section a
Section aSection a
Section a
hccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
hccit
 
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
hccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
hccit
 

Recently uploaded (20)

AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 

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