SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
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
• Passing Parameters
• Returning Values from Functions
• Composition
• Scope of Variables
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
Why Write Functions?
• Reusability
• Fewer errors introduced when code isn’t rewritten
• Reduces complexity of code
• Programs are easier to maintain
• Programs are easier to understand
5
Types of Functions
Different types of functions in Python:
Python built-in functions, Python recursion function, Python
lambda function, and Python user-defined functions with their
syntax and examples.
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
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
13
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
14
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.
15
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 Scope- A variable that’s declared inside a function has a local
scope. In other words, it is local to that function.
• 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()
• Global Scope- 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.
>>> y=7
>>> def func4():
print(y)
>>> func4()
16
Scope of variables, cont.
17
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
18
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)
19
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
20
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
21
Schematic of passing by reference
• Using memory location, actual value of original variable is changed
22
• 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
23
• 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.
24
• 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
25
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
26
• 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!
27
• 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!

Contenu connexe

Tendances (20)

Python Modules
Python ModulesPython Modules
Python Modules
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Python functions
Python functionsPython functions
Python functions
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python libraries
Python librariesPython libraries
Python libraries
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
 
Python
PythonPython
Python
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
Function in c
Function in cFunction in c
Function in c
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 

Similaire à Python functions

Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfSudhanshiBakre1
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptxzueZ3
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxSKUP1
 

Similaire à Python functions (20)

3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Functions
FunctionsFunctions
Functions
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Functions
Functions Functions
Functions
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 

Plus de Prof. Dr. K. Adisesha

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfProf. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfProf. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaProf. Dr. K. Adisesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaProf. Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfProf. Dr. K. Adisesha
 

Plus de Prof. Dr. K. Adisesha (20)

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
 
Operating System-adi.pdf
Operating System-adi.pdfOperating System-adi.pdf
Operating System-adi.pdf
 
Data_structure using C-Adi.pdf
Data_structure using C-Adi.pdfData_structure using C-Adi.pdf
Data_structure using C-Adi.pdf
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
 
JAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdfJAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdf
 

Dernier

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 

Dernier (20)

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

Python functions

  • 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 • Passing Parameters • Returning Values from Functions • Composition • Scope of Variables
  • 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 Why Write Functions? • Reusability • Fewer errors introduced when code isn’t rewritten • Reduces complexity of code • Programs are easier to maintain • Programs are easier to understand
  • 5. 5 Types of Functions Different types of functions in Python: Python built-in functions, Python recursion function, Python lambda function, and Python user-defined functions with their syntax and examples.
  • 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 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
  • 13. 13 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
  • 14. 14 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.
  • 15. 15 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 Scope- A variable that’s declared inside a function has a local scope. In other words, it is local to that function. • 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() • Global Scope- 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. >>> y=7 >>> def func4(): print(y) >>> func4()
  • 17. 17 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
  • 18. 18 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)
  • 19. 19 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
  • 20. 20 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
  • 21. 21 Schematic of passing by reference • Using memory location, actual value of original variable is changed
  • 22. 22 • 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
  • 23. 23 • 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.
  • 24. 24 • 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
  • 25. 25 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
  • 26. 26 • 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!
  • 27. 27 • 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!