SlideShare a Scribd company logo
Presented by
V Babu Ravipati
Unit -3
2
Functions
1. Reusability
2. Easy debugging
14. Python - Functions
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provides better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print() etc. but you
can also create your own functions. These functions are called user-defined functions.
Defining a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the
function name (shouldnot be keyword) and parentheses ( ) .
• Any input parameters or arguments should be placed within
these parentheses. You can also define parameters or
arguments inside these parentheses.
• The first statement of a function can be an optional statement
- the documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and
is indented.
• The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement
with no arguments is the same as return None.
Syntax:
def functionname( parameters ):
"function_docstring“
function_suite
[expression]
return
Example
Def add(a,b):
sum=a+b
return sum
a=int(input(“enter first number”))
b=int(input(“enter second number”))
res=add(a,b)
print(“result = “res)
Function Arguments:
A function by using the following types of formal arguments::
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
def printme( name, age):
print ("Name: ", name)
print ("Age ", age)
return;
printme(name=“Ramu”, age=29);
This would produce following result:
Name: Ramu
Age 29
Keyword arguments:
• Keyword arguments are related to the function calls.
When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter
name.
• This allows you to skip arguments or place them out
of order because the Python interpreter is able to
use the keywords provided to match the values with
parameters.
Following example gives more clear picture. Note, here order of the parameter
does not matter:
def printinfo( name, age ): "Test function"
print ("Name: ", name)
print ("Age ", age)
return
printinfo(age=50, name="miki" )
This would produce following result:
Name: miki Age 50
Default arguments:
A default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
Following example gives idea on default arguments, it would print default age
if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print ("Name: ", name)
print ("Age ", age)
return
printinfo( age=50, name="miki" )
printinfo( name="miki" )
This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that will hold the values of
all nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print ("Output is: “)
print (arg1)
for var in vartuple:
print var
return
printinfo( 10 )
printinfo( 70, 60, 50 )
This would produce following result:
Output is:
10
Output is:
70
60
50
Lambda Function
Lambda functions are also called anonymous
functions. An anonymous function is a
function defined without a name. As we
know to define a normal function in python,
we need to use the def keyword. But in this
case of anonymous functions, we use the
lambda keyword to define the functions.
The characteristics of lambda function
• The lambda function can take many
arguments but can return only one expression.
• Syntactically, lambda functions are restricted
to only a single expression.
• We can use them as an anonymous function
inside other functions.
• Lambda function is reusable.
Why should we use lambda functions?
Lambda functions are used when we
need a function for a short period of
time. This is commonly used when we
want to pass a function as an argument
to higher-order functions, that is,
functions that take other functions as
their arguments
Why should we use lambda functions?
Example
17
Fruitful Functions
Properties of Fruitful functions are
1. Return Value
2. Incremental Development
3. Composition
4. Boolean type
1.Return Value
def sum()
a=10
b=15
c=a+b
print(c)
Sum()
def sum(a,b)
c=a+b
return c
Print(sum(10,15))
def area(radius):
temp = 3.14159 * radius**2
return temp
def area(radius):
return 3.14159 * radius**2
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional.
def absolute_value(x):
if x < 0:
return -x
else:
return x
2.Incremental development
To deal with increasingly complex programs, we are
going to suggest a technique called incremental
development. The goal of incremental development is to
avoid long debugging sessions by adding and testing
only a small amount of code at a time.
As an example, suppose you want to find the distance
between two points, given by the coordinates (x1, y1)
and (x2, y2). By the Pythagorean theorem, the distance
is:
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
return 0.0
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
dx = x2 - x1
dy = y2 - y1
print 'dx is ', dx
print 'dy is ', dy
return 0.0
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
dx, dy = x2 - x1, y2 - y1
result =(dx**2 + dy**2)**0.5
return result
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
result =((x2-x1)**2 + (y2-y1)**2)**0.5
return result
def distance(x1, y1, x2, y2):
"""Return the distance between points
(x1, y1) and (x2, y2) as a float"""
return((x2-x1)**2 + (y2-y1)**2)**0.5
The key aspects of the process are:
1. Start with a working program and make small
incremental changes. At any point, if there is an error,
you will know exactly where it is.
2. Use temporary variables to hold intermediate values
so you can output and check them.
3. Once the program is working, you might want to
remove some of the scaffolding or consolidate
multiple statements into compound expressions, but
only if it does not make the program difficult to read.
3.Composition
As you should expect by now, you can call one function
from within another. This ability is called composition.
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
4.Creating Boolean functions
Functions that return a Boolean value
(True or False) can be used in
conditional statements (i.e. if…
else…)
05/02/09
Python Mini-Course: Day 2 - Lesson 8
28
is_divisible function
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
is_divisible(16,4)
is_divisible(16,3)
05/02/09
Python Mini-Course: Day 2 - Lesson 8
29
Scope of Variables:
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
Global vs. Local variables:
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared whereas global variables can be accessed throughout the program body by
all functions. When you call a function, the variables declared inside it are brought into
scope.
Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
There is one more example where argument is being passed by reference but inside the
function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
Print("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce
following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back
in the calling function. For example:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Name space
JNTUK python programming python unit 3.pptx

More Related Content

PPTX
Python Functions.pptx
PPTX
Python Functions.pptx
PPT
Python programming variables and comment
PPT
Powerpoint presentation for Python Functions
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPT
python slides introduction interrupt.ppt
PPT
functions modules and exceptions handlings.ppt
PPTX
Functions in Python Programming Language
Python Functions.pptx
Python Functions.pptx
Python programming variables and comment
Powerpoint presentation for Python Functions
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
python slides introduction interrupt.ppt
functions modules and exceptions handlings.ppt
Functions in Python Programming Language

Similar to JNTUK python programming python unit 3.pptx (20)

PPT
functions _
PPTX
Python programming - Functions and list and tuples
PPTX
2 Functions2.pptx
PPTX
Lecture 08.pptx
PPTX
functions.pptx
PDF
Unit 1-Part-5-Functions and Set Operations.pdf
PPTX
Functions in python, types of functions in python
PPT
PE1 Module 4.ppt
PPTX
ForLoopandUserDefinedFunctions.pptx
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
Unit 2 - Functions in python - Prof Jishnu M S
PPTX
Functions2.pptx
PPTX
functioninpython-1.pptx
PDF
functions- best.pdf
PDF
functions notes.pdf python functions and opp
PPTX
UNIT – 3.pptx for first year engineering
PPTX
Unit 2function in python.pptx
PPTX
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
PPTX
OOPS Object oriented Programming PPT Tutorial
functions _
Python programming - Functions and list and tuples
2 Functions2.pptx
Lecture 08.pptx
functions.pptx
Unit 1-Part-5-Functions and Set Operations.pdf
Functions in python, types of functions in python
PE1 Module 4.ppt
ForLoopandUserDefinedFunctions.pptx
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
Unit 2 - Functions in python - Prof Jishnu M S
Functions2.pptx
functioninpython-1.pptx
functions- best.pdf
functions notes.pdf python functions and opp
UNIT – 3.pptx for first year engineering
Unit 2function in python.pptx
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
OOPS Object oriented Programming PPT Tutorial
Ad

More from Venkateswara Babu Ravipati (14)

PPTX
PPT JNTUK python programming unit 2.pptx
PPTX
EG-Unit-2- Points.pptx
PPTX
PPTX
PPTX
inputoutput.pptx
PPTX
PP ECE A Sec UNIT-1.pptx
PPTX
python unit 2.pptx
PDF
PPTX
6-Python-Recursion PPT.pptx
PPTX
cad cam and robotics.pptx
PPTX
Le and ne algorithms
PPT JNTUK python programming unit 2.pptx
EG-Unit-2- Points.pptx
inputoutput.pptx
PP ECE A Sec UNIT-1.pptx
python unit 2.pptx
6-Python-Recursion PPT.pptx
cad cam and robotics.pptx
Le and ne algorithms
Ad

Recently uploaded (20)

PDF
Digital Logic Computer Design lecture notes
PPT
introduction to datamining and warehousing
DOCX
573137875-Attendance-Management-System-original
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPT
Project quality management in manufacturing
PPTX
additive manufacturing of ss316l using mig welding
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
composite construction of structures.pdf
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Digital Logic Computer Design lecture notes
introduction to datamining and warehousing
573137875-Attendance-Management-System-original
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Project quality management in manufacturing
additive manufacturing of ss316l using mig welding
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Lecture Notes Electrical Wiring System Components
Safety Seminar civil to be ensured for safe working.
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
OOP with Java - Java Introduction (Basics)
CYBER-CRIMES AND SECURITY A guide to understanding
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
composite construction of structures.pdf
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Internet of Things (IOT) - A guide to understanding
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf

JNTUK python programming python unit 3.pptx

  • 1. Presented by V Babu Ravipati Unit -3
  • 3. 14. Python - Functions A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions.
  • 4. Defining a Function Here are simple rules to define a function in Python: • Function blocks begin with the keyword def followed by the function name (shouldnot be keyword) and parentheses ( ) . • Any input parameters or arguments should be placed within these parentheses. You can also define parameters or arguments inside these parentheses. • The first statement of a function can be an optional statement - the documentation string of the function or docstring. • The code block within every function starts with a colon (:) and is indented. • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
  • 5. Syntax: def functionname( parameters ): "function_docstring“ function_suite [expression] return Example Def add(a,b): sum=a+b return sum a=int(input(“enter first number”)) b=int(input(“enter second number”)) res=add(a,b) print(“result = “res)
  • 6. Function Arguments: A function by using the following types of formal arguments:: • Required arguments • Keyword arguments • Default arguments • Variable-length arguments Required arguments: Required arguments are the arguments passed to a function in correct positional order. def printme( name, age): print ("Name: ", name) print ("Age ", age) return; printme(name=“Ramu”, age=29); This would produce following result: Name: Ramu Age 29
  • 7. Keyword arguments: • Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. • This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
  • 8. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print ("Name: ", name) print ("Age ", age) return printinfo(age=50, name="miki" ) This would produce following result: Name: miki Age 50
  • 9. Default arguments: A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): “Test function" print ("Name: ", name) print ("Age ", age) return printinfo( age=50, name="miki" ) printinfo( name="miki" ) This would produce following result: Name: miki Age 50 Name: miki Age 35
  • 10. Variable-length arguments: You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]
  • 11. An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" print ("Output is: “) print (arg1) for var in vartuple: print var return printinfo( 10 ) printinfo( 70, 60, 50 ) This would produce following result: Output is: 10 Output is: 70 60 50
  • 12. Lambda Function Lambda functions are also called anonymous functions. An anonymous function is a function defined without a name. As we know to define a normal function in python, we need to use the def keyword. But in this case of anonymous functions, we use the lambda keyword to define the functions.
  • 13. The characteristics of lambda function • The lambda function can take many arguments but can return only one expression. • Syntactically, lambda functions are restricted to only a single expression. • We can use them as an anonymous function inside other functions. • Lambda function is reusable.
  • 14. Why should we use lambda functions? Lambda functions are used when we need a function for a short period of time. This is commonly used when we want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments
  • 15. Why should we use lambda functions?
  • 17. 17 Fruitful Functions Properties of Fruitful functions are 1. Return Value 2. Incremental Development 3. Composition 4. Boolean type
  • 18. 1.Return Value def sum() a=10 b=15 c=a+b print(c) Sum() def sum(a,b) c=a+b return c Print(sum(10,15))
  • 19. def area(radius): temp = 3.14159 * radius**2 return temp def area(radius): return 3.14159 * radius**2 Sometimes it is useful to have multiple return statements, one in each branch of a conditional. def absolute_value(x): if x < 0: return -x else: return x
  • 20. 2.Incremental development To deal with increasingly complex programs, we are going to suggest a technique called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time. As an example, suppose you want to find the distance between two points, given by the coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is:
  • 21. def distance(x1, y1, x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" return 0.0
  • 22. def distance(x1, y1, x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" dx = x2 - x1 dy = y2 - y1 print 'dx is ', dx print 'dy is ', dy return 0.0
  • 23. def distance(x1, y1, x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" dx, dy = x2 - x1, y2 - y1 result =(dx**2 + dy**2)**0.5 return result
  • 24. def distance(x1, y1, x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" result =((x2-x1)**2 + (y2-y1)**2)**0.5 return result
  • 25. def distance(x1, y1, x2, y2): """Return the distance between points (x1, y1) and (x2, y2) as a float""" return((x2-x1)**2 + (y2-y1)**2)**0.5
  • 26. The key aspects of the process are: 1. Start with a working program and make small incremental changes. At any point, if there is an error, you will know exactly where it is. 2. Use temporary variables to hold intermediate values so you can output and check them. 3. Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.
  • 27. 3.Composition As you should expect by now, you can call one function from within another. This ability is called composition. def area2(xc, yc, xp, yp): radius = distance(xc, yc, xp, yp) result = area(radius) return result def area2(xc, yc, xp, yp): return area(distance(xc, yc, xp, yp))
  • 28. 4.Creating Boolean functions Functions that return a Boolean value (True or False) can be used in conditional statements (i.e. if… else…) 05/02/09 Python Mini-Course: Day 2 - Lesson 8 28
  • 29. is_divisible function def is_divisible(x, y): if x % y == 0: return True else: return False is_divisible(16,4) is_divisible(16,3) 05/02/09 Python Mini-Course: Day 2 - Lesson 8 29
  • 30. Scope of Variables: All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables Global vs. Local variables: Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
  • 31. Example: total = 0; # This is global variable. def sum( arg1, arg2 ): "Add both the parameters" total = arg1 + arg2; print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total This would produce following result: Inside the function local total : 30 Outside the function global total : 0
  • 32. There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): "This changes a passed list" mylist = [1,2,3,4]; print("Values inside the function: ", mylist) return mylist = [10,20,30]; changeme( mylist ); Print("Values outside the function: ", mylist) The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 33. Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: def changeme( mylist ): "This changes a passed list“ mylist.append([1,2,3,4]); print ("Values inside the function: ", mylist) return mylist = [10,20,30]; changeme( mylist ); print ("Values outside the function: ", mylist) So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]