SlideShare a Scribd company logo
Mohammad Hassan
Function
Objectives
● Why do we need functions?
● Where do function come from?
● How functions communicate with
their environment?
● Return a result from function
● Scopes in Python
● Creating multiparameter functions
Python Functions
● Define functions
● Passing arguments to Function
● Return a value from function
● Scope of Objects
● Default arguments
● Positional and keyword arguments
● Variable length arguments
Functions
• Piece of reusable code
• Solves particular task
• Call function instead of writing code yourself
• Tool to make life easier, and to simplify time-
consuming and tedious tasks
• A function is a block of organised, reusable
code that is used to perform a single, related
action. Functions provides better modularity
for your application and a high degree of code
reusing.
Built-in Functions
As you already know, Python gives you many built-in
functions like print() etc.
but you can also create your own functions. These
functions are called user-defined functions.
When to start writing your own functions
• If a particular fragment of the code begins to
appear in more than one place, consider the
possibility of isolating it in the form of a
function invoked from the points where the original
code was placed before.
• A good, attentive developer divides the code (or
more accurately: the problem) into well-isolated
pieces, and encodes each of them in the form of a
function. The process described here is often
called decomposition.
• If a piece of code becomes so large that reading
and understating it may cause a problem,
consider dividing it into separate, smaller
problems, and implement each of them in the
Where do the functions come from?
• Python- from Python itself ‒ we call these
functions built-in functions;
• Module -from Python's preinstalled modules ‒ a lot of
functions, very useful ones, but used significantly less
often than built-in ones, are available in a number of
modules installed together with Python
• Code- directly from your code
• there is one other possibility, but it's connected with
classes, so we'll omit it for now.
Defining a Function
Here are simple rules to define a function in Python:
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these
parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no
arguments is the same as return None.
Syntax:
Syntax:
By default, parameters have a positional behavior, and you need to
inform them in the same order that they were defined.
Example:
def printme( str ):
"This prints a passed string function"
print str
return
Defining a Function
How functions work
•when you invoke a function, Python remembers the place
where it happened and jumps into the invoked function;
•the body of the function is then executed;
•reaching the end of the function forces Python
to return to the place directly after the point of invocation.
Calling a Function
Following is the example to call printme() function:
def printme( str ): “This is a print function”
print str;
return;
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
This would produce following result:
I'm first call to user defined function!
Again second call to the same function
How functions communicate with their
environment
The function's full power reveals itself when it can be
equipped with an interface that is able to accept data provided
by the invoker. Such data can modify the function's behavior,
making it more flexible and adaptable to changing conditions.
A parameter is actually a variable, but there are two important
factors that make parameters different and special:
•parameters exist only inside functions in which they
have been defined, and the only place where the parameter
can be defined is a space between a pair of parentheses in
the def statement;
•assigning a value to the parameter is done at the time of
the function's invocation, by specifying the corresponding
argument.
def function(parameter):
###
Don't forget:
•parameters live inside functions (this is their natural
environment)
•arguments exist outside functions, and are carriers
of values passed to corresponding parameters.
How functions communicate with their
environment
def message(number):
###
The definition specifies that our function operates on just
one parameter named number. You can use it as an
ordinary variable, but only inside the function ‒ it isn't
visible anywhere else.
Let's now improve the function's body:
def message(number):
print("Enter a number:", number)
How functions communicate with their
environment
We've made use of the parameter. Note: we haven't
assigned the parameter with any value. Is it correct?
Yes, it is.
A value for the parameter will arrive from the function's
environment.
Remember: specifying one or more parameters in a
function's definition is also a requirement, and you
have to fulfil it during invocation. You must provide as
many arguments as there are defined parameters.
Failure to do so will cause an error.
How functions communicate with their
environment
def message(number):
print("Enter a number:", number)
Message()
TypeError: message() missing 1 required positional
argument: 'number’
def message(number):
print("Enter a number:", number)
message(1)
Enter a number: 1
How functions communicate with their
environment
It's legal, and possible, to have a variable named the same as a function's parameter.
def message(number):
print("Enter a number:", number)
number = 1234
message(1)
print(number)
A situation like this activates a mechanism called shadowing:
•parameter x shadows any variable of the same name, but...
•... only inside the function defining the parameter.
The parameter named number is a completely different entity from the variable named number.
A function can have as many parameters as you want, but the more parameters you have,
the harder it is to memorize their roles and purposes.
How functions communicate with their
environment
For a function there are following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Function Arguments:
Required arguments
Required arguments are the arguments passed to a function in correct
positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Positional parameter passing
A technique which assigns the ith (first, second, and so
on) argument to the ith (first, second, and so on) function
parameter is called positional parameter passing,
while arguments passed in this way are
named positional arguments.
def my_function(a, b, c):
print(a, b, c)
my_function(1, 2, 3)
Keyword argument
Python offers another convention for passing arguments, where the
meaning of the argument is dictated by its name, not by its position ‒
it's called keyword argument passing.
def introduction(first_name, last_name):
print("Hello, my name is", first_name, last_name)
introduction(first_name = "James", last_name = "Bond")
introduction(last_name = "Skywalker", first_name = "Luke")
The concept is clear ‒ the values passed to the parameters are
preceded by the target parameters' names, followed by the = sign.
The position doesn't matter here ‒ each argument's value knows its
destination on the basis of the name used.
Of course, you mustn't use a non-existent parameter name.
Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
This allows you to skip arguments or place them out of order because
the Python interpreter is able to use the keywords provided to match
the values with parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
This would produce following result:
My string
Following example gives more clear picture. Note, here order of the
parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
This would produce following result:
Name: miki Age 50
Keyword arguments
Mixing positional and keyword arguments
You can mix both styles if you want ‒ there is only one
unbreakable rule: you have to put positional arguments before
keyword arguments.
def adding(a, b, c):
print(a, "+", b, "+", c, "=", a + b + c)
adding(1, 2, 3) “Positional”
adding(c = 1, a = 2, b = 3) “Keyword”
adding(3, c = 1, b = 2) “Mixed”
will output:
1 + 2 + 3 = 6
2 + 3 + 1 = 6
3 + 2 + 1 = 6
It happens at times that a particular parameter's values are in use more often than
others. Such arguments may have their default (predefined) values taken into
consideration when their corresponding arguments have been omitted.
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
Following example gives idea on default arguments, it would print default age if it is
not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
This would produce following result:
Name: miki Age 50
Name: miki Age 35
Default arguments
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference.
It means if you change what a parameter refers to within a function, the
change also reflects back in the calling function. For example:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference
but inside the function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within
the function does not affect mylist. The function accomplishes nothing and finally
this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Pass by reference vs value
You may need to process a function for more arguments than you
specified while defining the function. These arguments are called
variable-length arguments and are not named in the function
definition, unlike required and default arguments.
The general syntax for a function with non-keyword variable
arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Variable-length arguments
An asterisk (*) is placed before the variable name that will hold the values of all nonkey word variable arguments.
This tuple remains empty if no additional arguments are specified during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
This would produce following result:
Output is:
10
Output is:
70
60
50
Variable-length arguments
Square function:Take one
arguments and prints its square
Square function:Take one
arguments and prints its square
Variable number of arguments
Effects and results: the return instruction
All the previously presented functions have some kind of
effect ‒ they produce some text and send it to the
console.
Of course, functions ‒ like their mathematical siblings ‒
may have results.
To get functions to return a value (but not only for this
purpose) you use the return instruction.
The return instruction has two different variants
return without an expression
def happy_new_year(wishes = True):
print("Three...")
print("Two...")
print("One...")
if not wishes:
return
print("Happy New Year!")
happy_new_year()
the output will look like this:
Three...
Two...
One...
Happy New Year!
Providing False as an argument:
happy_new_year(False)
the return instruction will cause its termination
just before the wishes ‒ this is the updated
output:
Three...
Two...
One...
return with an expression
The second return variant is extended with an expression:
def function():
return expression
There are two consequences of using it:
•it causes the immediate termination of the function's
execution (nothing new compared to the first variant)
• the function will evaluate the expression's value and will
return it (hence the name once again) as the function's
result.
return with an expression
def boring_function():
return 123
x = boring_function()
print("The boring_function has
returned its result. It's:", x)
The snippet writes the following text to the
console:
The boring_function has returned
its result. It's: 123
def boring_function():
print("'Boredom Mode' ON.")
return 123
print("This lesson is interesting!")
boring_function()
print("This lesson is boring...")
The program produces the following output:
This lesson is interesting!
'Boredom Mode' ON.
This lesson is boring...
•you are always allowed to ignore the function's result, and be satisfied with the
function's effect (if the function has any)
•if a function is intended to return a useful result, it must contain the second variant
of the return instruction.
Wait a minute ‒ does this mean that there are useless results, too? Yes, in some
sense.
A few words about None
None is a keyword.
Its data doesn't represent any reasonable value ‒
actually, it's not a value at all; hence, it mustn't take
part in any expressions.
print(None + 2)
will cause a runtime error, described by the following
diagnostic message:
TypeError: unsupported
operand type(s) for +: 'NoneType' and 'int'
A few words about None
value = None
if value is None:
print("Sorry, you don't carry any value")
if a function doesn't return a certain value using a return expression clause, it is assumed that
it implicitly returns None.
def strange_function(n):
if(n % 2 == 0):
return True
print(strange_function(2))
print(strange_function(1))
This is what we see in the console:
True
None
Effects and results: lists and
functions
May a list be sent to a function as an argument?
Of course it may! Any entity recognizable by Python can play the role of a function
argument, although it has to be assured that the function is able to cope with it.
def list_sum(lst):
s = 0
for elem in lst:
s += elem
return s
print(list_sum([5, 4, 3]))
will return 12 as a result
A single integer value mustn't be iterated through by the for loop.
print(list_sum(5)) will will return
TypeError: 'int' object is not iterable
May a list be a function result?
Yes, of course! Any entity recognizable by Python can be a function result.
def strange_list_fun(n):
strange_list = []
for i in range(0, n):
strange_list.insert(0, i)
return strange_list
print(strange_list_fun(5))
The program's output will look like this:
[4, 3, 2, 1, 0]
Effects and results: lists and functions
Functions and scopes
The scope of a name (e.g., a variable name) is the part
of a code where the name is properly recognizable.
For example, the scope of a function's parameter is the
function itself. The parameter is inaccessible outside the
function.
Does a variable's name propagate into a function's body?
def my_function():
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
The result of the test is positive ‒ the code outputs:
Do I know that variable? 1
1
A variable existing outside a function has scope inside the
function's body.
Functions and scopes
def my_function():
var = 2
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
The code produces a slightly different output now:
Do I know that variable? 2
1
•
Functions and scopes
•The var variable created inside the function is not the same as
when defined outside it ‒ it seems that there two different variables
of the same name;
• The function's variable shadows the variable coming from the
outside world.
A variable existing outside a function has scope inside the
function's body, excluding those which define a variable of the
same name.
It also means that the scope of a variable existing outside a
function is supported only when getting its value (reading).
Assigning a value forces the creation of the function's own variable
Functions and scopes
Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in
Python:
Global variables
Local variables
Global vs. Local variables:
Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
This means that local variables can be accessed only inside the function in
which they are declared whereas global variables can be accessed
throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope.
The global keyword
Does this mean that a function is not able to modify a variable
defined outside it?
Fortunately, the answer is no.
There's a special Python method which can extend a variable's
scope in a way which includes the function's body (even if you
want not only to read the values, but also to modify them).
Such an effect is caused by a keyword named global:
global name
global name1, name2, ...
Using Global keyword inside a function with the name (or names separated with commas) of a
variable (or variables), forces Python to refrain from creating a new variable inside the function
‒ the one accessible from outside will be used instead.
In other words, this name becomes global (it has global scope, and it doesn't matter whether
it's the subject of read or assign).
def my_function():
global var
var = 2
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
The global keyword
The code now outputs:
Do I know that variable?
2
Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Scope of Variables
Ad

More Related Content

Similar to Lecture 08.pptx (20)

Python functions
Python   functionsPython   functions
Python functions
Learnbay Datascience
 
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
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
KavithaChekuri3
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
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
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
KalaivaniD12
 
Notes5
Notes5Notes5
Notes5
hccit
 
functionnotes.pdf
functionnotes.pdffunctionnotes.pdf
functionnotes.pdf
AXL Computer Academy
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .
tarunsharmaug23
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
function in python programming languges .pptx
function in python programming languges .pptxfunction in python programming languges .pptx
function in python programming languges .pptx
rundalomary12
 
L14-L16 Functions.pdf
L14-L16 Functions.pdfL14-L16 Functions.pdf
L14-L16 Functions.pdf
DeepjyotiChoudhury4
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
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
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
KalaivaniD12
 
Notes5
Notes5Notes5
Notes5
hccit
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .
tarunsharmaug23
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
function in python programming languges .pptx
function in python programming languges .pptxfunction in python programming languges .pptx
function in python programming languges .pptx
rundalomary12
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 

Recently uploaded (20)

Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Ad

Lecture 08.pptx

  • 2. Objectives ● Why do we need functions? ● Where do function come from? ● How functions communicate with their environment? ● Return a result from function ● Scopes in Python ● Creating multiparameter functions
  • 3. Python Functions ● Define functions ● Passing arguments to Function ● Return a value from function ● Scope of Objects ● Default arguments ● Positional and keyword arguments ● Variable length arguments
  • 4. Functions • Piece of reusable code • Solves particular task • Call function instead of writing code yourself • Tool to make life easier, and to simplify time- consuming and tedious tasks • A function is a block of organised, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing.
  • 5. Built-in Functions As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions.
  • 6. When to start writing your own functions • If a particular fragment of the code begins to appear in more than one place, consider the possibility of isolating it in the form of a function invoked from the points where the original code was placed before. • A good, attentive developer divides the code (or more accurately: the problem) into well-isolated pieces, and encodes each of them in the form of a function. The process described here is often called decomposition. • If a piece of code becomes so large that reading and understating it may cause a problem, consider dividing it into separate, smaller problems, and implement each of them in the
  • 7. Where do the functions come from? • Python- from Python itself ‒ we call these functions built-in functions; • Module -from Python's preinstalled modules ‒ a lot of functions, very useful ones, but used significantly less often than built-in ones, are available in a number of modules installed together with Python • Code- directly from your code • there is one other possibility, but it's connected with classes, so we'll omit it for now.
  • 8. Defining a Function Here are simple rules to define a function in Python: Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Syntax:
  • 9. Syntax: By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined. Example: def printme( str ): "This prints a passed string function" print str return Defining a Function
  • 10. How functions work •when you invoke a function, Python remembers the place where it happened and jumps into the invoked function; •the body of the function is then executed; •reaching the end of the function forces Python to return to the place directly after the point of invocation.
  • 11. Calling a Function Following is the example to call printme() function: def printme( str ): “This is a print function” print str; return; printme("I'm first call to user defined function!"); printme("Again second call to the same function"); This would produce following result: I'm first call to user defined function! Again second call to the same function
  • 12. How functions communicate with their environment The function's full power reveals itself when it can be equipped with an interface that is able to accept data provided by the invoker. Such data can modify the function's behavior, making it more flexible and adaptable to changing conditions. A parameter is actually a variable, but there are two important factors that make parameters different and special: •parameters exist only inside functions in which they have been defined, and the only place where the parameter can be defined is a space between a pair of parentheses in the def statement; •assigning a value to the parameter is done at the time of the function's invocation, by specifying the corresponding argument.
  • 13. def function(parameter): ### Don't forget: •parameters live inside functions (this is their natural environment) •arguments exist outside functions, and are carriers of values passed to corresponding parameters. How functions communicate with their environment
  • 14. def message(number): ### The definition specifies that our function operates on just one parameter named number. You can use it as an ordinary variable, but only inside the function ‒ it isn't visible anywhere else. Let's now improve the function's body: def message(number): print("Enter a number:", number) How functions communicate with their environment
  • 15. We've made use of the parameter. Note: we haven't assigned the parameter with any value. Is it correct? Yes, it is. A value for the parameter will arrive from the function's environment. Remember: specifying one or more parameters in a function's definition is also a requirement, and you have to fulfil it during invocation. You must provide as many arguments as there are defined parameters. Failure to do so will cause an error. How functions communicate with their environment
  • 16. def message(number): print("Enter a number:", number) Message() TypeError: message() missing 1 required positional argument: 'number’ def message(number): print("Enter a number:", number) message(1) Enter a number: 1 How functions communicate with their environment
  • 17. It's legal, and possible, to have a variable named the same as a function's parameter. def message(number): print("Enter a number:", number) number = 1234 message(1) print(number) A situation like this activates a mechanism called shadowing: •parameter x shadows any variable of the same name, but... •... only inside the function defining the parameter. The parameter named number is a completely different entity from the variable named number. A function can have as many parameters as you want, but the more parameters you have, the harder it is to memorize their roles and purposes. How functions communicate with their environment
  • 18. For a function there are following types of formal arguments:  Required arguments  Keyword arguments  Default arguments  Variable-length arguments Function Arguments:
  • 19. Required arguments Required arguments are the arguments passed to a function in correct positional order. def printme( str ): "This prints a passed string" print str; return; printme(); This would produce following result: Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)
  • 20. Positional parameter passing A technique which assigns the ith (first, second, and so on) argument to the ith (first, second, and so on) function parameter is called positional parameter passing, while arguments passed in this way are named positional arguments. def my_function(a, b, c): print(a, b, c) my_function(1, 2, 3)
  • 21. Keyword argument Python offers another convention for passing arguments, where the meaning of the argument is dictated by its name, not by its position ‒ it's called keyword argument passing. def introduction(first_name, last_name): print("Hello, my name is", first_name, last_name) introduction(first_name = "James", last_name = "Bond") introduction(last_name = "Skywalker", first_name = "Luke") The concept is clear ‒ the values passed to the parameters are preceded by the target parameters' names, followed by the = sign. The position doesn't matter here ‒ each argument's value knows its destination on the basis of the name used. Of course, you mustn't use a non-existent parameter name.
  • 22. Keyword arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. def printme( str ): "This prints a passed string" print str; return; printme( str = "My string"); This would produce following result: My string
  • 23. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); This would produce following result: Name: miki Age 50 Keyword arguments
  • 24. Mixing positional and keyword arguments You can mix both styles if you want ‒ there is only one unbreakable rule: you have to put positional arguments before keyword arguments. def adding(a, b, c): print(a, "+", b, "+", c, "=", a + b + c) adding(1, 2, 3) “Positional” adding(c = 1, a = 2, b = 3) “Keyword” adding(3, c = 1, b = 2) “Mixed” will output: 1 + 2 + 3 = 6 2 + 3 + 1 = 6 3 + 2 + 1 = 6
  • 25. It happens at times that a particular parameter's values are in use more often than others. Such arguments may have their default (predefined) values taken into consideration when their corresponding arguments have been omitted. A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): “Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); printinfo( name="miki" ); This would produce following result: Name: miki Age 50 Name: miki Age 35 Default arguments
  • 26. Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: def changeme( mylist ): "This changes a passed list“ mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
  • 27. There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): "This changes a passed list" mylist = [1,2,3,4]; print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] Pass by reference vs value
  • 28. You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] Variable-length arguments
  • 29. An asterisk (*) is placed before the variable name that will hold the values of all nonkey word variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" print "Output is: " print arg1 for var in vartuple: print var return; printinfo( 10 ); printinfo( 70, 60, 50 ); This would produce following result: Output is: 10 Output is: 70 60 50 Variable-length arguments
  • 30. Square function:Take one arguments and prints its square
  • 31. Square function:Take one arguments and prints its square
  • 32. Variable number of arguments
  • 33. Effects and results: the return instruction All the previously presented functions have some kind of effect ‒ they produce some text and send it to the console. Of course, functions ‒ like their mathematical siblings ‒ may have results. To get functions to return a value (but not only for this purpose) you use the return instruction. The return instruction has two different variants
  • 34. return without an expression def happy_new_year(wishes = True): print("Three...") print("Two...") print("One...") if not wishes: return print("Happy New Year!") happy_new_year() the output will look like this: Three... Two... One... Happy New Year! Providing False as an argument: happy_new_year(False) the return instruction will cause its termination just before the wishes ‒ this is the updated output: Three... Two... One...
  • 35. return with an expression The second return variant is extended with an expression: def function(): return expression There are two consequences of using it: •it causes the immediate termination of the function's execution (nothing new compared to the first variant) • the function will evaluate the expression's value and will return it (hence the name once again) as the function's result.
  • 36. return with an expression def boring_function(): return 123 x = boring_function() print("The boring_function has returned its result. It's:", x) The snippet writes the following text to the console: The boring_function has returned its result. It's: 123 def boring_function(): print("'Boredom Mode' ON.") return 123 print("This lesson is interesting!") boring_function() print("This lesson is boring...") The program produces the following output: This lesson is interesting! 'Boredom Mode' ON. This lesson is boring... •you are always allowed to ignore the function's result, and be satisfied with the function's effect (if the function has any) •if a function is intended to return a useful result, it must contain the second variant of the return instruction. Wait a minute ‒ does this mean that there are useless results, too? Yes, in some sense.
  • 37. A few words about None None is a keyword. Its data doesn't represent any reasonable value ‒ actually, it's not a value at all; hence, it mustn't take part in any expressions. print(None + 2) will cause a runtime error, described by the following diagnostic message: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
  • 38. A few words about None value = None if value is None: print("Sorry, you don't carry any value") if a function doesn't return a certain value using a return expression clause, it is assumed that it implicitly returns None. def strange_function(n): if(n % 2 == 0): return True print(strange_function(2)) print(strange_function(1)) This is what we see in the console: True None
  • 39. Effects and results: lists and functions May a list be sent to a function as an argument? Of course it may! Any entity recognizable by Python can play the role of a function argument, although it has to be assured that the function is able to cope with it. def list_sum(lst): s = 0 for elem in lst: s += elem return s print(list_sum([5, 4, 3])) will return 12 as a result A single integer value mustn't be iterated through by the for loop. print(list_sum(5)) will will return TypeError: 'int' object is not iterable
  • 40. May a list be a function result? Yes, of course! Any entity recognizable by Python can be a function result. def strange_list_fun(n): strange_list = [] for i in range(0, n): strange_list.insert(0, i) return strange_list print(strange_list_fun(5)) The program's output will look like this: [4, 3, 2, 1, 0] Effects and results: lists and functions
  • 41. Functions and scopes The scope of a name (e.g., a variable name) is the part of a code where the name is properly recognizable. For example, the scope of a function's parameter is the function itself. The parameter is inaccessible outside the function.
  • 42. Does a variable's name propagate into a function's body? def my_function(): print("Do I know that variable?", var) var = 1 my_function() print(var) The result of the test is positive ‒ the code outputs: Do I know that variable? 1 1 A variable existing outside a function has scope inside the function's body. Functions and scopes
  • 43. def my_function(): var = 2 print("Do I know that variable?", var) var = 1 my_function() print(var) The code produces a slightly different output now: Do I know that variable? 2 1 • Functions and scopes
  • 44. •The var variable created inside the function is not the same as when defined outside it ‒ it seems that there two different variables of the same name; • The function's variable shadows the variable coming from the outside world. A variable existing outside a function has scope inside the function's body, excluding those which define a variable of the same name. It also means that the scope of a variable existing outside a function is supported only when getting its value (reading). Assigning a value forces the creation of the function's own variable Functions and scopes
  • 45. Scope of Variables All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables Global vs. Local variables: Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
  • 46. The global keyword Does this mean that a function is not able to modify a variable defined outside it? Fortunately, the answer is no. There's a special Python method which can extend a variable's scope in a way which includes the function's body (even if you want not only to read the values, but also to modify them). Such an effect is caused by a keyword named global: global name global name1, name2, ...
  • 47. Using Global keyword inside a function with the name (or names separated with commas) of a variable (or variables), forces Python to refrain from creating a new variable inside the function ‒ the one accessible from outside will be used instead. In other words, this name becomes global (it has global scope, and it doesn't matter whether it's the subject of read or assign). def my_function(): global var var = 2 print("Do I know that variable?", var) var = 1 my_function() print(var) The global keyword The code now outputs: Do I know that variable? 2
  • 48. Example: total = 0; # This is global variable. def sum( arg1, arg2 ): "Add both the parameters" total = arg1 + arg2; print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total This would produce following result: Inside the function local total : 30 Outside the function global total : 0 Scope of Variables