SlideShare a Scribd company logo
FUNCTIONS
Prof. K. Adisesha
BE, M.Sc., M.Th., NET, (Ph.D.)
2
Learning objectives
• Understanding Functions
• Defining Functions in Python
• Flow of Execution in a Function Call
• Scope of Variables
• Passing Parameters
• Returning Values from Functions
• Function Composition
3
What Are Functions?
• A function is a block of code which only runs when it is
called.
• Functions are sub-programs which perform tasks which may
need to be repeated.
• Some functions are “bundled” in standard libraries which are
part of any language’s core package. We’ve already used
many built-in functions, such as input(), eval(), etc.
• Functions are similar to methods, but may not be connected
with objects
• Programmers can write their own functions
4
Functions
Advantages of Using functions
• Program development made easy and fast:
• Program testing becomes easy
• Code sharing becomes possible
• Code re-usability increases
• Increases program readability
• Function facilitates procedural abstraction
• Functions facilitate the factoring of code
• Programs are easier to understand
5
Types of Functions
Different types of functions in Python:
• Python user-defined functions
• Python built-in functions
• Python lambda function
• Python recursion function
6
User-Defined Functions
• Python lets us group a sequence of statements into a single
entity, called a function.
• A Python function may or may not have a name.
Advantages of User-defined Functions in Python
▪ This Python Function help divide a program into modules. This
makes the code easier to manage, debug, and scale.
▪ It implements code reuse. Every time you need to execute a
sequence of statements, all you need to do is to call the
function.
▪ This Python Function allow us to change functionality easily,
and different programmers can work on different functions.
7
Function Elements
• Before we can use functions we have to define them.
• So there are two main elements to functions:
1. Define the function. The function definition can appear at the
beginning or end of the program file.
def my_function():
print("Hello from a function")
2. Invoke or call the function. This usually happens in the body
of the main() function, but sub-functions can call other sub-
functions too.
main():
my_function()
8
Rules for naming function
(identifier)
• We follow the same rules when naming a function as we do
when naming a variable.
• It can begin with either of the following: A-Z, a-z, and
underscore(_).
• The rest of it can contain either of the following: A-Z, a-z,
digits(0-9), and underscore(_).
• A reserved keyword may not be chosen as an identifier.
• It is good practice to name a Python function according to
what it does.
9
Function definitions
• A function definition has two major parts: the definition
head and the definition body.
• The definition head in Python has three main parts: the
keyword def, the identifier or name of the function, and the
parameters in parentheses.
def average(total, num):
• def - keyword
• Average-- identifier
• total, num-- Formal parameters or arguments
• Don’t forget the colon : to mark the start of a statement
bloc
10
Function body
• The colon at the end of the definition head marks the start
of the body, the bloc of statements. There is no symbol to
mark the end of the bloc, but remember that indentation in
Python controls statement blocs.
def average(total, num):
x = total/num #Function body
return x #The value that’s returned when the
function is invoked
11
Workshop
Using the small function defined in the last slide, write a command line
program which asks the user for a test score total and the number of
students taking the test. The program should print the test score average.
• Example: Function Flow - happy.py
# Simple illustration of functions.
def happy():
print "Happy Birthday to you!"
def sing(person):
happy()
print "Happy birthday, dear", person + "."
def main():
sing(“Sunny")
print
main()
12
Function Variable
Scope of Variables in function:
• A variable’s scope tells us where in the program it is visible.
• There are three types of variables with the view of scope
▪ Local variable:
• Accessible only inside the functional block where it is
declared.
▪ Global variable :
• Variable which is accessible among whole program using
global keyword.
▪ Non local variable:
• Accessible in nesting of functions, using non local keyword.
13
Scope of variables
• A variable’s scope tells us where in the program it is visible. A
variable may have local or global scope.
Local variable:
• A variable that’s declared inside a function has a local scope. In
other words, it is local to that function.
• Accessible only inside the functional block where it is declared.
• Thus it is possible to have two variables named the same within one
source code file, but they will be different variables if they’re in
different functions—and they could be different data types as well.
>>> def func3():
x=7
print(x)
>>> func3()
14
Scope of variables
Global variable:
• When you declare a variable outside python function, or anything
else, it has global scope. It means that it is visible everywhere
within the program.
• Example: Global variables in nested function
15
Scope of variables
Non local variable:
• Accessible in nesting of functions, using non local keyword.
• Example: Non local variable in a function
16
Scope of variables, cont.
17
Parameters or Arguments
• The terms parameter and argument can be used for the same thing:
information that are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in the function
definition.
• An argument is the value that are sent to the function when it is called.
• Arguments are often shortened to args in Python documentations.
• By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you
have to call the function with 2 arguments, not more, and not less.
def my_function(fname, lname): Parameters
print(fname + " " + lname)
my_function(“Narayana", “College") Arguments
18
Function Arguments
Function Arguments:
• Functions can be called using following types of formal
arguments −
• Required arguments/Positional parameter -arguments passed in
correct positional order.
• Keyword arguments -the caller identifies the arguments by the
parameter name.
• Default arguments -that assumes a default value if a value is not
provided to arg.
• Variable-length arguments –pass multiple values with single
argument name.
19
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example: If the number of arguments is unknown, add a * before the parameter name:
def my_function(*name):
print("The youngest child is " + name[2])
my_function(“Rekha", “Prajwal", “Sunny")
Output: The youngest child is Sunny
• If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the function
definition.
• This way the function will receive a dictionary of arguments, and can access
the items accordingly:
def my_function(**name):
print("His last name is " + name["lname"])
my_function(fname = “Prajwal", lname = “Sunny")
Output: His last name is Sunny
20
Formal vs. Actual Parameters
(and Arguments)
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
21
Functions: Return values
• Some functions don’t have any parameters or any return values, such as
functions that just display. But…
• “return” keyword lets a function return a value, use the return statement:
def square(x): # x is Formal parameter
return x * x #Return value
• The call: output = square(3)
The pass Statement
• function definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass statement to avoid getting an error.
Example
def myfunction():
pass
22
Return value as argument
Return value used as argument:
• Example of calculating a hypotenuse
num1, num2 = 10, 14
Hypotenuse = math.sqrt(sum_of_squares(num1, num2))
def sum_of_squares(x,y):
t = (x*x) + (y * y)
return t
Returning more than one value
• Functions can return more than one value
def hi_low(x,y):
if x >= y:
return x, y
else: return y, x
• The call:
hiNum, lowNum = hi_low(data1, data2)
23
Functions modifying parameters
• So far we’ve seen that functions can accept values (actual parameters), process
data, and return a value to the calling function. But the variables that were
handed to the invoked function weren’t changed. The called function just
worked on the VALUES of those actual parameters, and then returned a new
value, which is usually stored in a variable by the calling function. This is called
passing parameters by value
24
Functions Properties
Mutable/Immutable properties of data objects w/r function
• Everything in Python is an object, and every objects in
Python can be either mutable or immutable.
• In Python, every variable holds an object instance. When an
object is initiated, it is assigned a unique object id.
• Its type is defined at run time and once set as mutable
object or an immutable object:
▪ Mutable objects:
• list, dict, set, byte array
▪ Immutable objects:
• int, float, complex, string, tuple, frozen set, bytes
25
Modifying parameters, cont.
• Some programming languages, like C++, allow passing parameters by reference.
Essentially this means that special syntax is used when defining and calling
functions so that the function parameters refer to the memory location of the
original variable, not just the value stored there.
• Schematic of passing by value
• PYTHON DOES NOT SUPPORT PASSING PARAMETERS BY REFERENCE
26
Schematic of passing by reference
• Using memory location, actual value of original variable is changed
27
• Python does NOT support passing by reference, BUT…
• Python DOES support passing lists, the values of which can
be changed by subfunctions.
• Example of Python’s mutable parameters
Passing lists in Python
28
• Because a list is actually a Python object with values associated with it,
when a list is passed as a parameter to a subfunction the memory
location of that list object is actually passed –not all the values of the list.
• When just a variable is passed, only the value is passed, not the memory
location of that variable.
• E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
• Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Output:
apple
banana
cherry
Passing lists, cont.
29
Mathematical functions:
• Mathematical functions are available under math module. To
use mathematical functions under this module, we have to
import the module using import math.
• Example
▪ To use sqrt() function:
Import math
r=math.sqrt(4)
print(r)
▪ OUTPUT:
2.0
Built-in Functions
30
Functions available in Python Math Module:
Built-in Functions
31
• Python also accepts function recursion, which means a defined function can call
itself.
• Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
• The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.
• Example:
def Recursion(k):
if(k > 0):
result = k + Recursion(k - 1)
print(result)
else:
result = 0
return result
print("nnRecursion Example Results")
Recursion(6)
Recursion
32
Python Lambda
• A lambda function is a small anonymous function.
• The power of lambda is better shown when you use them as an
anonymous function inside another function.
• A lambda function can take any number of arguments, but can only
have one expression.
• Syntax
lambda arguments : expression
• The expression is executed and the result is returned:
• Example
▪ A lambda function that adds 10 to the number passed in as an
argument, and print the result:
x = lambda a : a + 10
print(x(5))
Output: 15
33
• Functions are useful in any program because they allow us
to break down a complicated algorithm into executable
subunits. Hence the functionalities of a program are easier
to understand. This is called modularization.
• If a module (function) is going to be used more than once
in a program, it’s particular useful—it’s reusable. E.g., if
interest rates had to be recalculated yearly, one subfunction
could be called repeatedly.
Modularize!
34
• We learned about the Python function.
• Types of Functions
• Advantages of a user-defined function in Python
• Function Parameters, arguments and return a value.
• We also looked at the scope and lifetime of a variable.
Thank you
Conclusion!
Ad

More Related Content

Similar to 3-Python Functions.pdf in simple......... (20)

Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions ConceptsFunctions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Functions
FunctionsFunctions
Functions
Golda Margret Sheeba J
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the numberDecided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions ConceptsFunctions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the numberDecided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 

Recently uploaded (20)

Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Ad

3-Python Functions.pdf in simple.........

  • 1. FUNCTIONS Prof. K. Adisesha BE, M.Sc., M.Th., NET, (Ph.D.)
  • 2. 2 Learning objectives • Understanding Functions • Defining Functions in Python • Flow of Execution in a Function Call • Scope of Variables • Passing Parameters • Returning Values from Functions • Function Composition
  • 3. 3 What Are Functions? • A function is a block of code which only runs when it is called. • Functions are sub-programs which perform tasks which may need to be repeated. • Some functions are “bundled” in standard libraries which are part of any language’s core package. We’ve already used many built-in functions, such as input(), eval(), etc. • Functions are similar to methods, but may not be connected with objects • Programmers can write their own functions
  • 4. 4 Functions Advantages of Using functions • Program development made easy and fast: • Program testing becomes easy • Code sharing becomes possible • Code re-usability increases • Increases program readability • Function facilitates procedural abstraction • Functions facilitate the factoring of code • Programs are easier to understand
  • 5. 5 Types of Functions Different types of functions in Python: • Python user-defined functions • Python built-in functions • Python lambda function • Python recursion function
  • 6. 6 User-Defined Functions • Python lets us group a sequence of statements into a single entity, called a function. • A Python function may or may not have a name. Advantages of User-defined Functions in Python ▪ This Python Function help divide a program into modules. This makes the code easier to manage, debug, and scale. ▪ It implements code reuse. Every time you need to execute a sequence of statements, all you need to do is to call the function. ▪ This Python Function allow us to change functionality easily, and different programmers can work on different functions.
  • 7. 7 Function Elements • Before we can use functions we have to define them. • So there are two main elements to functions: 1. Define the function. The function definition can appear at the beginning or end of the program file. def my_function(): print("Hello from a function") 2. Invoke or call the function. This usually happens in the body of the main() function, but sub-functions can call other sub- functions too. main(): my_function()
  • 8. 8 Rules for naming function (identifier) • We follow the same rules when naming a function as we do when naming a variable. • It can begin with either of the following: A-Z, a-z, and underscore(_). • The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_). • A reserved keyword may not be chosen as an identifier. • It is good practice to name a Python function according to what it does.
  • 9. 9 Function definitions • A function definition has two major parts: the definition head and the definition body. • The definition head in Python has three main parts: the keyword def, the identifier or name of the function, and the parameters in parentheses. def average(total, num): • def - keyword • Average-- identifier • total, num-- Formal parameters or arguments • Don’t forget the colon : to mark the start of a statement bloc
  • 10. 10 Function body • The colon at the end of the definition head marks the start of the body, the bloc of statements. There is no symbol to mark the end of the bloc, but remember that indentation in Python controls statement blocs. def average(total, num): x = total/num #Function body return x #The value that’s returned when the function is invoked
  • 11. 11 Workshop Using the small function defined in the last slide, write a command line program which asks the user for a test score total and the number of students taking the test. The program should print the test score average. • Example: Function Flow - happy.py # Simple illustration of functions. def happy(): print "Happy Birthday to you!" def sing(person): happy() print "Happy birthday, dear", person + "." def main(): sing(“Sunny") print main()
  • 12. 12 Function Variable Scope of Variables in function: • A variable’s scope tells us where in the program it is visible. • There are three types of variables with the view of scope ▪ Local variable: • Accessible only inside the functional block where it is declared. ▪ Global variable : • Variable which is accessible among whole program using global keyword. ▪ Non local variable: • Accessible in nesting of functions, using non local keyword.
  • 13. 13 Scope of variables • A variable’s scope tells us where in the program it is visible. A variable may have local or global scope. Local variable: • A variable that’s declared inside a function has a local scope. In other words, it is local to that function. • Accessible only inside the functional block where it is declared. • Thus it is possible to have two variables named the same within one source code file, but they will be different variables if they’re in different functions—and they could be different data types as well. >>> def func3(): x=7 print(x) >>> func3()
  • 14. 14 Scope of variables Global variable: • When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program. • Example: Global variables in nested function
  • 15. 15 Scope of variables Non local variable: • Accessible in nesting of functions, using non local keyword. • Example: Non local variable in a function
  • 17. 17 Parameters or Arguments • The terms parameter and argument can be used for the same thing: information that are passed into a function. • From a function's perspective: • A parameter is the variable listed inside the parentheses in the function definition. • An argument is the value that are sent to the function when it is called. • Arguments are often shortened to args in Python documentations. • By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. def my_function(fname, lname): Parameters print(fname + " " + lname) my_function(“Narayana", “College") Arguments
  • 18. 18 Function Arguments Function Arguments: • Functions can be called using following types of formal arguments − • Required arguments/Positional parameter -arguments passed in correct positional order. • Keyword arguments -the caller identifies the arguments by the parameter name. • Default arguments -that assumes a default value if a value is not provided to arg. • Variable-length arguments –pass multiple values with single argument name.
  • 19. 19 Arbitrary Arguments, *args • If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. • This way the function will receive a tuple of arguments, and can access the items accordingly: Example: If the number of arguments is unknown, add a * before the parameter name: def my_function(*name): print("The youngest child is " + name[2]) my_function(“Rekha", “Prajwal", “Sunny") Output: The youngest child is Sunny • If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. • This way the function will receive a dictionary of arguments, and can access the items accordingly: def my_function(**name): print("His last name is " + name["lname"]) my_function(fname = “Prajwal", lname = “Sunny") Output: His last name is Sunny
  • 20. 20 Formal vs. Actual Parameters (and Arguments) • Information can be passed into functions as arguments. • Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
  • 21. 21 Functions: Return values • Some functions don’t have any parameters or any return values, such as functions that just display. But… • “return” keyword lets a function return a value, use the return statement: def square(x): # x is Formal parameter return x * x #Return value • The call: output = square(3) The pass Statement • function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error. Example def myfunction(): pass
  • 22. 22 Return value as argument Return value used as argument: • Example of calculating a hypotenuse num1, num2 = 10, 14 Hypotenuse = math.sqrt(sum_of_squares(num1, num2)) def sum_of_squares(x,y): t = (x*x) + (y * y) return t Returning more than one value • Functions can return more than one value def hi_low(x,y): if x >= y: return x, y else: return y, x • The call: hiNum, lowNum = hi_low(data1, data2)
  • 23. 23 Functions modifying parameters • So far we’ve seen that functions can accept values (actual parameters), process data, and return a value to the calling function. But the variables that were handed to the invoked function weren’t changed. The called function just worked on the VALUES of those actual parameters, and then returned a new value, which is usually stored in a variable by the calling function. This is called passing parameters by value
  • 24. 24 Functions Properties Mutable/Immutable properties of data objects w/r function • Everything in Python is an object, and every objects in Python can be either mutable or immutable. • In Python, every variable holds an object instance. When an object is initiated, it is assigned a unique object id. • Its type is defined at run time and once set as mutable object or an immutable object: ▪ Mutable objects: • list, dict, set, byte array ▪ Immutable objects: • int, float, complex, string, tuple, frozen set, bytes
  • 25. 25 Modifying parameters, cont. • Some programming languages, like C++, allow passing parameters by reference. Essentially this means that special syntax is used when defining and calling functions so that the function parameters refer to the memory location of the original variable, not just the value stored there. • Schematic of passing by value • PYTHON DOES NOT SUPPORT PASSING PARAMETERS BY REFERENCE
  • 26. 26 Schematic of passing by reference • Using memory location, actual value of original variable is changed
  • 27. 27 • Python does NOT support passing by reference, BUT… • Python DOES support passing lists, the values of which can be changed by subfunctions. • Example of Python’s mutable parameters Passing lists in Python
  • 28. 28 • Because a list is actually a Python object with values associated with it, when a list is passed as a parameter to a subfunction the memory location of that list object is actually passed –not all the values of the list. • When just a variable is passed, only the value is passed, not the memory location of that variable. • E.g. if you send a List as an argument, it will still be a List when it reaches the function: • Example def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) Output: apple banana cherry Passing lists, cont.
  • 29. 29 Mathematical functions: • Mathematical functions are available under math module. To use mathematical functions under this module, we have to import the module using import math. • Example ▪ To use sqrt() function: Import math r=math.sqrt(4) print(r) ▪ OUTPUT: 2.0 Built-in Functions
  • 30. 30 Functions available in Python Math Module: Built-in Functions
  • 31. 31 • Python also accepts function recursion, which means a defined function can call itself. • Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result. • The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming. • Example: def Recursion(k): if(k > 0): result = k + Recursion(k - 1) print(result) else: result = 0 return result print("nnRecursion Example Results") Recursion(6) Recursion
  • 32. 32 Python Lambda • A lambda function is a small anonymous function. • The power of lambda is better shown when you use them as an anonymous function inside another function. • A lambda function can take any number of arguments, but can only have one expression. • Syntax lambda arguments : expression • The expression is executed and the result is returned: • Example ▪ A lambda function that adds 10 to the number passed in as an argument, and print the result: x = lambda a : a + 10 print(x(5)) Output: 15
  • 33. 33 • Functions are useful in any program because they allow us to break down a complicated algorithm into executable subunits. Hence the functionalities of a program are easier to understand. This is called modularization. • If a module (function) is going to be used more than once in a program, it’s particular useful—it’s reusable. E.g., if interest rates had to be recalculated yearly, one subfunction could be called repeatedly. Modularize!
  • 34. 34 • We learned about the Python function. • Types of Functions • Advantages of a user-defined function in Python • Function Parameters, arguments and return a value. • We also looked at the scope and lifetime of a variable. Thank you Conclusion!
  翻译: