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
• 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!
Ad

Recommended

Python Functions
Python Functions
Mohammed Sikander
 
Python file handling
Python file handling
Prof. Dr. K. Adisesha
 
Functions in python slide share
Functions in python slide share
Devashish Kumar
 
File handling in Python
File handling in Python
Megha V
 
Functions in python
Functions in python
colorsof
 
List,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
MatplotLib.pptx
MatplotLib.pptx
Paras Intotech
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Object oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Variables in python
Variables in python
Jaya Kumari
 
Functions in Python
Functions in Python
Kamal Acharya
 
Python set
Python set
Mohammed Sikander
 
Python programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python OOPs
Python OOPs
Binay Kumar Ray
 
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Packages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Classes and objects
Classes and objects
Nilesh Dalvi
 
Introduction to Python
Introduction to Python
Mohammed Sikander
 
Modules and packages in python
Modules and packages in python
TMARAGATHAM
 
Class, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Chapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Functions in Python
Functions in Python
Shakti Singh Rathore
 
C++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 

More Related Content

What's hot (20)

Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Object oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Variables in python
Variables in python
Jaya Kumari
 
Functions in Python
Functions in Python
Kamal Acharya
 
Python set
Python set
Mohammed Sikander
 
Python programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python OOPs
Python OOPs
Binay Kumar Ray
 
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Packages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Classes and objects
Classes and objects
Nilesh Dalvi
 
Introduction to Python
Introduction to Python
Mohammed Sikander
 
Modules and packages in python
Modules and packages in python
TMARAGATHAM
 
Class, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Chapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Functions in Python
Functions in Python
Shakti Singh Rathore
 
C++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Variables in python
Variables in python
Jaya Kumari
 
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Packages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Classes and objects
Classes and objects
Nilesh Dalvi
 
Modules and packages in python
Modules and packages in python
TMARAGATHAM
 
Class, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
C++ OOPS Concept
C++ OOPS Concept
Boopathi K
 

Similar to Python functions (20)

2_3 Functions 5d.pptx2_3 Functions 5d.pptx
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions_new.pptx
Functions_new.pptx
Yagna15
 
python slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
FUNCTIONengineeringtechnologyslidesh.pptx
FUNCTIONengineeringtechnologyslidesh.pptx
ricknova674
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Functions
Functions
Golda Margret Sheeba J
 
UNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Functions
Functions
Dr.Subha Krishna
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions in Python and its types for beginners
Functions in Python and its types for beginners
Mohammad Usman
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Functions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Python Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptx
AnuragBharti27
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions_new.pptx
Functions_new.pptx
Yagna15
 
python slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
FUNCTIONengineeringtechnologyslidesh.pptx
FUNCTIONengineeringtechnologyslidesh.pptx
ricknova674
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions in Python and its types for beginners
Functions in Python and its types for beginners
Mohammad Usman
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Functions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Ad

More from Prof. Dr. K. Adisesha (20)

MACHINE LEARNING Notes by Dr. K. Adisesha
MACHINE LEARNING Notes by Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Prof. Dr. K. Adisesha
 
Genetic Algorithm in Machine Learning PPT by-Adi
Genetic Algorithm in Machine Learning PPT by-Adi
Prof. Dr. K. Adisesha
 
Unsupervised Machine Learning PPT Adi.pdf
Unsupervised Machine Learning PPT Adi.pdf
Prof. Dr. K. Adisesha
 
Supervised Machine Learning PPT by K. Adisesha
Supervised Machine Learning PPT by K. Adisesha
Prof. Dr. K. Adisesha
 
Introduction to Machine Learning PPT by K. Adisesha
Introduction to Machine Learning PPT by K. Adisesha
Prof. Dr. K. Adisesha
 
Design and Analysis of Algorithms ppt by K. Adi
Design and Analysis of Algorithms ppt by K. Adi
Prof. Dr. K. Adisesha
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
Prof. Dr. K. Adisesha
 
Operating System-4 "File Management" by Adi.pdf
Operating System-4 "File Management" by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-3 "Memory Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System Concepts Part-1 by_Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-2_Process Managementby_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Prof. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
Prof. Dr. K. Adisesha
 
MACHINE LEARNING Notes by Dr. K. Adisesha
MACHINE LEARNING Notes by Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Prof. Dr. K. Adisesha
 
Genetic Algorithm in Machine Learning PPT by-Adi
Genetic Algorithm in Machine Learning PPT by-Adi
Prof. Dr. K. Adisesha
 
Unsupervised Machine Learning PPT Adi.pdf
Unsupervised Machine Learning PPT Adi.pdf
Prof. Dr. K. Adisesha
 
Supervised Machine Learning PPT by K. Adisesha
Supervised Machine Learning PPT by K. Adisesha
Prof. Dr. K. Adisesha
 
Introduction to Machine Learning PPT by K. Adisesha
Introduction to Machine Learning PPT by K. Adisesha
Prof. Dr. K. Adisesha
 
Design and Analysis of Algorithms ppt by K. Adi
Design and Analysis of Algorithms ppt by K. Adi
Prof. Dr. K. Adisesha
 
Data Structure using C by Dr. K Adisesha .ppsx
Data Structure using C by Dr. K Adisesha .ppsx
Prof. Dr. K. Adisesha
 
Operating System-4 "File Management" by Adi.pdf
Operating System-4 "File Management" by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-3 "Memory Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System Concepts Part-1 by_Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-2_Process Managementby_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Prof. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
Prof. Dr. K. Adisesha
 
Ad

Recently uploaded (20)

Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 

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!