Movatterモバイル変換


[0]ホーム

URL:


Uploaded byBeulahS2
PPTX, PDF306 views

Functions in Python Programming Language

User defined functions, Recursive functions and lambda functions

Embed presentation

Download to read offline
FUNCTIONS IN PYTHONPREPARED BY,Dr. S. Beulah,ASP/ Dept. of CA/ NICHE
Introduction A function is a block of organized and reusable programcode that performs a single, specific and well defined task. A function is a block of code which only runs when it iscalled. You can pass data, known as parameters, into a function. A function can return data as a result.
Defining a function When a function is defined space is allocated for that function in thememory. A function definition comprises of two parts.1. Function Header2. Function Body In Python a function is defined using the def keyword: Give the function name after def keyword followed by parentheses in which arguments aregiven End with colon (:) Inside the function add the program statements to be executed End with or without return statement
Contd… The general format is given:function headerdef function_name(var1, var2, ….):documentation stringstatement block function bodyreturn[expression] Example:def my_function():print("Hello from function")my_function() The indented statements from body of the function
Function Call The function call statement invokes the function. When a function is invoked the program control jumps to the called functionto execute the statements that are a part of that function. Once the called function is executed the program control passes back to thecalling function. The syntax of calling a function that does not accept parameters is simplythe name of the function followed by parenthesis, which is given as,function_name()
Contd… Function call statement has the following syntax when it accepts parameters:function_name(var1, var2,….) When the function is called the interpreter checks that the correct numberand type of arguments are used in the function call. It also checks the type of the returned valueNote:--> List of variables used in function call is known as the actual parameterlist.-> The actual parameter list may be variable names, expressions orconstants.
Function Parameters A function can take parameters which are nothing but some values that arepasses to it so that the function can manipulate them to produce the desiredresult. These parameters are normal variables with a small difference that the valuesof these variables are defined when we call the function and are then passedto the function. Parameters are specified within the pair of parenthesis in the functiondefinition and are separated by commas.Key points to remember while calling the function:-> The function name and the number of arguments in the function callmust be same as that given in the function definition.
-> If by mistake the parameters passed to a function are more than that it isspecified to accept, then an error will be returned.Example:-def funct(i, j):print(“Hello World”,i,j)funct(5)Output:-Type Error-> If by mistake the parameters passed to a function are less than that it isspecified to accept, then an error will be returned.
Example:-def funct(i):print(“Hello World”,i)funct(5, 5)Output:-Type Error-> Names of variables in function call and header of function definition mayvary.Example:-def funct(i):print(“Hello World”,i)j = 10funct(j)Output:-Hello World 10
FRUITFUL FUNCTIONS
Introduction A fruitful function is one in which there is a return statement with anexpression. This means that a fruitful function returns a value that can be utilized bythe calling function for further processing.
The Return Statement To let a function return a value, use the return statement: Every function has an implicit return statement as the last instruction inthe function body. This implicit return statement returns nothing to its caller, so it is saidto return none. But you can change this default behaviour by explicitly using thereturn statement to return some value back to the caller. The syntax of return statement isreturn(expression)
Note:--> A function may or may not return a value. The return statement is used for two things:1. Return a value to the caller2. To end and exit a function and go back to its caller.Example:-def cube(x):return(x*x*x)num = 10result = cube(3)print(“Cube = ”, result)Output:-Cube = 27
 Key points to remember: The return statement must appear within the function Once you return a value from a function it immediately exits that function.Therefore, any code written after the return statement is never executed.
Parameters 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 acomma. The following example has a function with one argument (fname). Whenthe function is called, we pass along a first name, which is used insidethe function to print the full name:
 Example:-def my_function(fname):print(fname + “Mr.")my_function("Emil")my_function("Tobias")my_function("Linus")Parameters or Arguments? The terms parameter and argument can be used for the same thing: informationthat are passed into a function.
Types of Arguments Required Arguments Keyword Arguments Default Arguments Variable-Length Arguments
Required Arguments In the required arguments the arguments are passed to a function in correctpositional order. Also the number of arguments in the function call should exactly match with thenumber of arguments specified in the function definition.Example:-def display(str):print(str)str =“Hello”display(str)Output:-Hello
Keyword Arguments You can also send arguments with the key = value syntax. Python allows functions to be called using keyword arguments in which theorder of the arguments can be changed. The values are not assigned to arguments according to their position butbased on their name.Example:-def my_function(child3, child2, child1):print("The youngest child is " + child3)my_function(child1 = "Emil",child2="Tobias",child3 = "Linus")Output:-The youngest child is Linus
Key points to remember: All the keyword arguments passed should match one of the argumentsaccepted by the function. The order of keyword arguments is not important. In no case an argument should receive a value more than once.
Default Arguments Python allows function arguments to have default values. If thefunction is called without the argument, the argument gets itsdefault value. The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value:def my_function(country = "Norway"):print("I am from " + country)my_function("Sweden")my_function("India")my_function()my_function("Brazil")
Key Points to remember You can specify any number of default arguments in your function. If you have default arguments Then they must be written after thenon-default arguments. This means that non-default argumentscannot follow default arguments.Example:-def display(name, course =“MCA”, marks)print(name, course, marks)display(name = “Riya”,85)Output:-Syntax error
Variable – Length Arguments Python allows programmers to make function calls with arbitrary(or any)number of arguments. When we use arbitrary arguments or variable length arguments then thefunction definition uses an asterisk(*) before the parameter name. The syntax is given:def function_name([arg1,arg2,…], *var_args_tuple):function_statementsreturn [expression]
Example:-def funct(name, *subjects):print(name,”likes to read”)for s in subjects:print(s,”t”)funct(“Abinesh”,”Maths”,”Science”)funct(“Riya”,”C”,”C++”,”Pascal”,”Java”,”Python”)funct(“Abi”)Output:-Abinesh likes to read Maths ScienceRiya likes to read C C++ Pascal Java PythonAbi likes to read
LAMBDA FUNCTIONSORANONYMOUS FUNCTIONS
Introduction A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only haveone expression. They are not declared as other functions using the def keyword. Lambda functions contain only a single line. Syntax is given:lambda arguments:expression The arguments contain a comma separated list of arguments and theexpression in an arithmetic expression that uses these arguments.
Example:- Add 10 to argument a, and return the result:x = lambda a : a + 10print(x(5)) Lambda functions can take any number of arguments: Multiply argument a with argument b and return the result:x = lambda a, b : a * bprint(x(5, 6)) Summarize argument a, b, and c and return the result:x = lambda a, b, c : a + b + cprint(x(5, 6, 2))
Key Points to Remember:1. Lambda functions have no name.2. Lambda functions can take any number of arguments.3. Lambda functions can return just one value in the form of an expression.4. Lambda function definition does not have an explicit return statementbut it always contain an expression which is returned.5. They are a one line version of a function and hence cannot containmultiple expressions.6. They cannot access variables other than those in their parameter list.7. Lambda functions cannot even access global variables.8. You can pass lambda functions as arguments in other functions.
 Program that passes lambda function as an argument to a function.def func(f, n):print(n)twice = lambda x: x *2thrice = lambda x:x * 3func(twice, 4)func(thrice, 3)
Recursive Functions
Introduction A recursive function is defined as a function that calls itself to solve asmaller version of its task until a final call is made which does not require acall to itself. Every recursive solution has two major cases.1. Base case – in which the problem is simple enough to be solveddirectly without making any further calls to the same function.2. Recursive case – in which first the problem at hand is divided intosimpler sub parts. Second the function calls itself but with sub parts of theproblem obtained in the first step. Third, the result is obtained by combiningthe solutions of simpler sub-parts.
 To calculate the factorial of a numberdef fact(n):if(n==1 or n==0):return 1else:return n * fact(n-1)n = int(input(“Enter n:”))print(“Factorial = ”, fact(n))Output:-Enter n:5Factorial = 120
Recursion with IterationRecursion is more of a top-down approach to problem solving in whichthe original problem is divided into smaller sub-problems.Iteration follows a bottom-up approach that begins with what is knownand then constructing the solution step-by-step.Benefits:- Recursive solutions often tend to be shorter and simpler than non-recursiveones. Code is clearer and easier to use. Recursion uses the original formula to solve a problem. It follows a divide and conquer technique to solve a problems. In some instances, recursion may be more efficient.
Limitations:- For some programmers and readers recursion is a difficult concept. Recursion is implemented using system stack. Using a recursive function takes more memory and time to execute ascompared to its non-recursive counterpart. It is difficult to find bugs, particularly when using global variables.

Recommended

PPTX
Functions in python slide share
PPT
Powerpoint presentation for Python Functions
PPT
functions _
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PPT
Python programming variables and comment
PPTX
JNTUK python programming python unit 3.pptx
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
PPTX
Python Functions.pptx
PPT
python slides introduction interrupt.ppt
PDF
Python Function.pdf
PDF
Python functions
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PPTX
Working with functions the minumum ppt.pptx
PPTX
Functions in python, types of functions in python
PPTX
Learn more about the concepts Functions of Python
PPTX
Lecture 08.pptx
PDF
3-Python Functions.pdf in simple.........
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
UNIT 3 python.pptx
PPTX
_Python_ Functions _and_ Libraries_.pptx
PPTX
Python_Functions_Modules_ User define Functions-
PPTX
Chapter 2 Python Functions
PPTX
Function in Python function in python.pptx
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPTX
functions new.pptx
PDF
PRIZ Academy - Thinking The Skill Everyone Forgot
PPTX
CEC369 IoT P CEC369 IoT P CEC369 IoT PCEC369 IoT PCEC369 IoT P

More Related Content

PPTX
Functions in python slide share
PPT
Powerpoint presentation for Python Functions
PPT
functions _
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PPT
Python programming variables and comment
PPTX
JNTUK python programming python unit 3.pptx
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
Functions in python slide share
Powerpoint presentation for Python Functions
functions _
PYTHON_FUNCTIONS in Detail user defined and Built In
Python programming variables and comment
JNTUK python programming python unit 3.pptx
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...

Similar to Functions in Python Programming Language

PPTX
Python Functions.pptx
PPT
python slides introduction interrupt.ppt
PDF
Python Function.pdf
PDF
Python functions
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PPTX
Working with functions the minumum ppt.pptx
PPTX
Functions in python, types of functions in python
PPTX
Learn more about the concepts Functions of Python
PPTX
Lecture 08.pptx
PDF
3-Python Functions.pdf in simple.........
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
UNIT 3 python.pptx
PPTX
_Python_ Functions _and_ Libraries_.pptx
PPTX
Python_Functions_Modules_ User define Functions-
PPTX
Chapter 2 Python Functions
PPTX
Function in Python function in python.pptx
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPTX
functions new.pptx
Python Functions.pptx
python slides introduction interrupt.ppt
Python Function.pdf
Python functions
04. WORKING WITH FUNCTIONS-2 (1).pptx
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
Working with functions the minumum ppt.pptx
Functions in python, types of functions in python
Learn more about the concepts Functions of Python
Lecture 08.pptx
3-Python Functions.pdf in simple.........
Python for Data Science function third module ppt.pptx
 
UNIT 3 python.pptx
_Python_ Functions _and_ Libraries_.pptx
Python_Functions_Modules_ User define Functions-
Chapter 2 Python Functions
Function in Python function in python.pptx
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
functions new.pptx

Recently uploaded

PDF
PRIZ Academy - Thinking The Skill Everyone Forgot
PPTX
CEC369 IoT P CEC369 IoT P CEC369 IoT PCEC369 IoT PCEC369 IoT P
PDF
Stern-Gerlach-Experiment from quantum mechanics
PPTX
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
PPTX
Control Structures and Looping Basics Understanding Control Flow and Loops Co...
PDF
Advancements in Telecommunication for Disaster Management (www.kiu.ac.ug)
PDF
@Regenerative braking system of DC motor
PPTX
DevFest Seattle 2025 - AI Native Design Patterns.pptx
PPTX
ensemble learning of machine learning .pptx
PDF
Small Space Big Design - Amar DeXign Scape
PPTX
Principles of Energy Efficiency_ Doing More with Less
PPT
lec13.ppt FOR COMPOSITES AND POLYMERS MATERIAL SCIENCE
PDF
Best Marketplaces to Buy Snapchat Accounts in 2025.pdf
PDF
Welcome to ISPR 2026 - 12th International Conference on Image and Signal Pro...
PPTX
introduction-to-maintenance- Dr. Munthear Alqaderi
PPTX
AI at the Crossroads_ Transforming the Future of Green Technology.pptx
PPTX
Supercapacitor.pptx...............................
PPTX
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
PPTX
TRANSPORTATION ENGINEERING Unit-5.1.pptx
PPTX
TRANSPORTATION ENGINEERING Unit-5.2.pptx
PRIZ Academy - Thinking The Skill Everyone Forgot
CEC369 IoT P CEC369 IoT P CEC369 IoT PCEC369 IoT PCEC369 IoT P
Stern-Gerlach-Experiment from quantum mechanics
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
Control Structures and Looping Basics Understanding Control Flow and Loops Co...
Advancements in Telecommunication for Disaster Management (www.kiu.ac.ug)
@Regenerative braking system of DC motor
DevFest Seattle 2025 - AI Native Design Patterns.pptx
ensemble learning of machine learning .pptx
Small Space Big Design - Amar DeXign Scape
Principles of Energy Efficiency_ Doing More with Less
lec13.ppt FOR COMPOSITES AND POLYMERS MATERIAL SCIENCE
Best Marketplaces to Buy Snapchat Accounts in 2025.pdf
Welcome to ISPR 2026 - 12th International Conference on Image and Signal Pro...
introduction-to-maintenance- Dr. Munthear Alqaderi
AI at the Crossroads_ Transforming the Future of Green Technology.pptx
Supercapacitor.pptx...............................
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
TRANSPORTATION ENGINEERING Unit-5.1.pptx
TRANSPORTATION ENGINEERING Unit-5.2.pptx

Functions in Python Programming Language

  • 1.
    FUNCTIONS IN PYTHONPREPAREDBY,Dr. S. Beulah,ASP/ Dept. of CA/ NICHE
  • 2.
    Introduction A functionis a block of organized and reusable programcode that performs a single, specific and well defined task. A function is a block of code which only runs when it iscalled. You can pass data, known as parameters, into a function. A function can return data as a result.
  • 3.
    Defining a functionWhen a function is defined space is allocated for that function in thememory. A function definition comprises of two parts.1. Function Header2. Function Body In Python a function is defined using the def keyword: Give the function name after def keyword followed by parentheses in which arguments aregiven End with colon (:) Inside the function add the program statements to be executed End with or without return statement
  • 4.
    Contd… The generalformat is given:function headerdef function_name(var1, var2, ….):documentation stringstatement block function bodyreturn[expression] Example:def my_function():print("Hello from function")my_function() The indented statements from body of the function
  • 5.
    Function Call Thefunction call statement invokes the function. When a function is invoked the program control jumps to the called functionto execute the statements that are a part of that function. Once the called function is executed the program control passes back to thecalling function. The syntax of calling a function that does not accept parameters is simplythe name of the function followed by parenthesis, which is given as,function_name()
  • 6.
    Contd… Function callstatement has the following syntax when it accepts parameters:function_name(var1, var2,….) When the function is called the interpreter checks that the correct numberand type of arguments are used in the function call. It also checks the type of the returned valueNote:--> List of variables used in function call is known as the actual parameterlist.-> The actual parameter list may be variable names, expressions orconstants.
  • 7.
    Function Parameters Afunction can take parameters which are nothing but some values that arepasses to it so that the function can manipulate them to produce the desiredresult. These parameters are normal variables with a small difference that the valuesof these variables are defined when we call the function and are then passedto the function. Parameters are specified within the pair of parenthesis in the functiondefinition and are separated by commas.Key points to remember while calling the function:-> The function name and the number of arguments in the function callmust be same as that given in the function definition.
  • 8.
    -> If bymistake the parameters passed to a function are more than that it isspecified to accept, then an error will be returned.Example:-def funct(i, j):print(“Hello World”,i,j)funct(5)Output:-Type Error-> If by mistake the parameters passed to a function are less than that it isspecified to accept, then an error will be returned.
  • 9.
    Example:-def funct(i):print(“Hello World”,i)funct(5,5)Output:-Type Error-> Names of variables in function call and header of function definition mayvary.Example:-def funct(i):print(“Hello World”,i)j = 10funct(j)Output:-Hello World 10
  • 10.
  • 11.
    Introduction A fruitfulfunction is one in which there is a return statement with anexpression. This means that a fruitful function returns a value that can be utilized bythe calling function for further processing.
  • 12.
    The Return StatementTo let a function return a value, use the return statement: Every function has an implicit return statement as the last instruction inthe function body. This implicit return statement returns nothing to its caller, so it is saidto return none. But you can change this default behaviour by explicitly using thereturn statement to return some value back to the caller. The syntax of return statement isreturn(expression)
  • 13.
    Note:--> A functionmay or may not return a value. The return statement is used for two things:1. Return a value to the caller2. To end and exit a function and go back to its caller.Example:-def cube(x):return(x*x*x)num = 10result = cube(3)print(“Cube = ”, result)Output:-Cube = 27
  • 14.
     Key pointsto remember: The return statement must appear within the function Once you return a value from a function it immediately exits that function.Therefore, any code written after the return statement is never executed.
  • 15.
    Parameters Information canbe 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 acomma. The following example has a function with one argument (fname). Whenthe function is called, we pass along a first name, which is used insidethe function to print the full name:
  • 16.
     Example:-def my_function(fname):print(fname+ “Mr.")my_function("Emil")my_function("Tobias")my_function("Linus")Parameters or Arguments? The terms parameter and argument can be used for the same thing: informationthat are passed into a function.
  • 17.
    Types of ArgumentsRequired Arguments Keyword Arguments Default Arguments Variable-Length Arguments
  • 18.
    Required Arguments Inthe required arguments the arguments are passed to a function in correctpositional order. Also the number of arguments in the function call should exactly match with thenumber of arguments specified in the function definition.Example:-def display(str):print(str)str =“Hello”display(str)Output:-Hello
  • 19.
    Keyword Arguments Youcan also send arguments with the key = value syntax. Python allows functions to be called using keyword arguments in which theorder of the arguments can be changed. The values are not assigned to arguments according to their position butbased on their name.Example:-def my_function(child3, child2, child1):print("The youngest child is " + child3)my_function(child1 = "Emil",child2="Tobias",child3 = "Linus")Output:-The youngest child is Linus
  • 20.
    Key points toremember: All the keyword arguments passed should match one of the argumentsaccepted by the function. The order of keyword arguments is not important. In no case an argument should receive a value more than once.
  • 21.
    Default Arguments Pythonallows function arguments to have default values. If thefunction is called without the argument, the argument gets itsdefault value. The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value:def my_function(country = "Norway"):print("I am from " + country)my_function("Sweden")my_function("India")my_function()my_function("Brazil")
  • 22.
    Key Points toremember You can specify any number of default arguments in your function. If you have default arguments Then they must be written after thenon-default arguments. This means that non-default argumentscannot follow default arguments.Example:-def display(name, course =“MCA”, marks)print(name, course, marks)display(name = “Riya”,85)Output:-Syntax error
  • 23.
    Variable – LengthArguments Python allows programmers to make function calls with arbitrary(or any)number of arguments. When we use arbitrary arguments or variable length arguments then thefunction definition uses an asterisk(*) before the parameter name. The syntax is given:def function_name([arg1,arg2,…], *var_args_tuple):function_statementsreturn [expression]
  • 24.
    Example:-def funct(name, *subjects):print(name,”likesto read”)for s in subjects:print(s,”t”)funct(“Abinesh”,”Maths”,”Science”)funct(“Riya”,”C”,”C++”,”Pascal”,”Java”,”Python”)funct(“Abi”)Output:-Abinesh likes to read Maths ScienceRiya likes to read C C++ Pascal Java PythonAbi likes to read
  • 25.
  • 26.
    Introduction A lambdafunction is a small anonymous function. A lambda function can take any number of arguments, but can only haveone expression. They are not declared as other functions using the def keyword. Lambda functions contain only a single line. Syntax is given:lambda arguments:expression The arguments contain a comma separated list of arguments and theexpression in an arithmetic expression that uses these arguments.
  • 27.
    Example:- Add 10to argument a, and return the result:x = lambda a : a + 10print(x(5)) Lambda functions can take any number of arguments: Multiply argument a with argument b and return the result:x = lambda a, b : a * bprint(x(5, 6)) Summarize argument a, b, and c and return the result:x = lambda a, b, c : a + b + cprint(x(5, 6, 2))
  • 28.
    Key Points toRemember:1. Lambda functions have no name.2. Lambda functions can take any number of arguments.3. Lambda functions can return just one value in the form of an expression.4. Lambda function definition does not have an explicit return statementbut it always contain an expression which is returned.5. They are a one line version of a function and hence cannot containmultiple expressions.6. They cannot access variables other than those in their parameter list.7. Lambda functions cannot even access global variables.8. You can pass lambda functions as arguments in other functions.
  • 29.
     Program thatpasses lambda function as an argument to a function.def func(f, n):print(n)twice = lambda x: x *2thrice = lambda x:x * 3func(twice, 4)func(thrice, 3)
  • 30.
  • 31.
    Introduction A recursivefunction is defined as a function that calls itself to solve asmaller version of its task until a final call is made which does not require acall to itself. Every recursive solution has two major cases.1. Base case – in which the problem is simple enough to be solveddirectly without making any further calls to the same function.2. Recursive case – in which first the problem at hand is divided intosimpler sub parts. Second the function calls itself but with sub parts of theproblem obtained in the first step. Third, the result is obtained by combiningthe solutions of simpler sub-parts.
  • 32.
     To calculatethe factorial of a numberdef fact(n):if(n==1 or n==0):return 1else:return n * fact(n-1)n = int(input(“Enter n:”))print(“Factorial = ”, fact(n))Output:-Enter n:5Factorial = 120
  • 33.
    Recursion with IterationRecursionis more of a top-down approach to problem solving in whichthe original problem is divided into smaller sub-problems.Iteration follows a bottom-up approach that begins with what is knownand then constructing the solution step-by-step.Benefits:- Recursive solutions often tend to be shorter and simpler than non-recursiveones. Code is clearer and easier to use. Recursion uses the original formula to solve a problem. It follows a divide and conquer technique to solve a problems. In some instances, recursion may be more efficient.
  • 34.
    Limitations:- For someprogrammers and readers recursion is a difficult concept. Recursion is implemented using system stack. Using a recursive function takes more memory and time to execute ascompared to its non-recursive counterpart. It is difficult to find bugs, particularly when using global variables.

[8]ページ先頭

©2009-2025 Movatter.jp