Movatterモバイル変換


[0]ホーム

URL:


PPT, PDF11 views

python slides introduction interrupt.ppt

python slides

Embed presentation

Download to read offline
14. Python - Functions• A function is a block of organized, reusable code that is used toperform a single, related action. Functions provides better modularityfor your application and a high degree of code reusing.• As you already know, Python gives you many built-in functions likeprint() etc. but you can also create your own functions. These functionsare called user-defined functions.
Defining a FunctionHere are simple rules to define a function in Python:• Function blocks begin with the keyword def followed by the functionname and parentheses ( ( ) ).• Any input parameters or arguments should be placed within theseparentheses. You can also define parameters inside theseparentheses.• The first statement of a function can be an optional statement - thedocumentation string of the function or docstring.• The code block within every function starts with a colon (:) and isindented.• The statement return [expression] exits a function, optionally passingback an expression to the caller. A return statement with noarguments is the same as return None.• Syntax:• def functionname( parameters ):• "function_docstring" function_suite return [expression]
• Syntax:def functionname( parameters ):"function_docstring"function_suitereturn [expression]By default, parameters have a positional behavior, and you needto inform them in the same order that they were defined.• Example:def printme( str ):"This prints a passed string function"print strreturn
Calling a Function• Following is the example to call printme() function:def printme( str ): "This is a print function“print str;return;printme("I'm first call to user defined function!");printme("Again second call to the same function");• This would produce following result:I'm first call to user defined function!Again second call to the same function
Pass by reference vs valueAll parameters (arguments) in the Python language are passed byreference. It means if you change what a parameter refers to within afunction, the change also reflects back in the calling function. Forexample:def changeme( mylist ): "This changes a passed list“mylist.append([1,2,3,4]);print "Values inside the function: ", mylistreturnmylist = [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]]
There is one more example where argument is being passed by reference butinside 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: ", mylistreturnmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist• The parameter mylist is local to the function changeme. Changing mylistwithin the function does not affect mylist. The function accomplishesnothing and finally this would produce following result:Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]
Function Arguments:A function by using the following types of formal arguments::– Required arguments– Keyword arguments– Default arguments– Variable-length argumentsRequired arguments:• Required arguments are the arguments passed to a function in correctpositional order.def printme( str ): "This prints a passed string"print str;return;printme();• This would produce following result:Traceback (most recent call last):File "test.py", line 11, in <module> printme();TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments:• Keyword arguments are related to the function calls. When youuse keyword arguments in a function call, the caller identifiesthe arguments by the parameter name.• This allows you to skip arguments or place them out of orderbecause the Python interpreter is able to use the keywordsprovided to match the values with parameters.def printme( str ): "This prints a passed string"print str;return;printme( str = "My string");• This would produce following result:My string
Following example gives more clear picture. Note, here order ofthe 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 defaultvalue if a value is not provided in the function call for thatargument.• Following example gives idea on default arguments, it wouldprint 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 thanyou specified while defining the function. These arguments arecalled variable-length arguments and are not named in thefunction definition, unlike required and default arguments.• The general syntax for a function with non-keyword variablearguments is this:def functionname([formal_args,] *var_args_tuple ):"function_docstring"function_suitereturn [expression]
• An asterisk (*) is placed before the variable name that will hold thevalues of all nonkeyword variable arguments. This tuple remainsempty if no additional arguments are specified during the functioncall. For example:def printinfo( arg1, *vartuple ):"This is test"print "Output is: "print arg1for var in vartuple:print varreturn;printinfo( 10 );printinfo( 70, 60, 50 );• This would produce following result:Output is:10Output is:706050
The Anonymous Functions:You can use the lambda keyword to create small anonymous functions.These functions are called anonymous because they are not declaredin the standard manner by using the def keyword.• Lambda forms can take any number of arguments but return just onevalue in the form of an expression. They cannot contain commands ormultiple expressions.• An anonymous function cannot be a direct call to print becauselambda requires an expression.• Lambda functions have their own local namespace and cannot accessvariables other than those in their parameter list and those in theglobal namespace.• Although it appears that lambda's are a one-line version of a function,they are not equivalent to inline statements in C or C++, whosepurpose is by passing function stack allocation during invocation forperformance reasons.• Syntax:lambda [arg1 [,arg2,.....argn]]:expression
Example:• Following is the example to show how lembda form of functionworks:sum = lambda arg1, arg2: arg1 + arg2;print "Value of total : ", sum( 10, 20 )print "Value of total : ", sum( 20, 20 )• This would produce following result:Value of total : 30Value of total : 40
Scope of Variables:• All variables in a program may not be accessible at all locations in thatprogram. This depends on where you have declared a variable.• The scope of a variable determines the portion of the program whereyou can access a particular identifier. There are two basic scopes ofvariables in Python:Global variablesLocal 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 thefunction in which they are declared whereas global variables can beaccessed throughout the program body by all functions. When you calla 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 : ", totalreturn total;# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total• This would produce following result:Inside the function local total : 30Outside the function global total : 0

Recommended

PPT
functions modules and exceptions handlings.ppt
PPT
Python programming variables and comment
PPT
functions _
PPTX
Python Functions.pptx
PPTX
Python programming - Functions and list and tuples
PPTX
JNTUK python programming python unit 3.pptx
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PDF
Unit 1-Part-5-Functions and Set Operations.pdf
PPTX
Functions in Python Programming Language
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PPTX
Lecture 08.pptx
PPTX
Functions in python slide share
PDF
3-Python Functions.pdf in simple.........
PPTX
functions.pptx
PPTX
functioninpython-1.pptx
PPTX
UNIT 3 python.pptx
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
_Python_ Functions _and_ Libraries_.pptx
PDF
Functions2.pdf
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PPTX
Chapter 2 Python Functions
PPTX
Functions in Python with all type of arguments
PDF
functions- best.pdf
PPTX
2 Functions2.pptx
PPT
python introduction to user friendly.ppt
PPTX
python for data anal gh i o fytysis creation.pptx

More Related Content

PPT
functions modules and exceptions handlings.ppt
PPT
Python programming variables and comment
PPT
functions _
PPTX
Python Functions.pptx
PPTX
Python programming - Functions and list and tuples
PPTX
JNTUK python programming python unit 3.pptx
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
functions modules and exceptions handlings.ppt
Python programming variables and comment
functions _
Python Functions.pptx
Python programming - Functions and list and tuples
JNTUK python programming python unit 3.pptx
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Py-Slides-3 difficultpythoncoursefforbeginners.ppt

Similar to python slides introduction interrupt.ppt

PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PDF
Unit 1-Part-5-Functions and Set Operations.pdf
PPTX
Functions in Python Programming Language
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PPTX
Lecture 08.pptx
PPTX
Functions in python slide share
PDF
3-Python Functions.pdf in simple.........
PPTX
functions.pptx
PPTX
functioninpython-1.pptx
PPTX
UNIT 3 python.pptx
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
_Python_ Functions _and_ Libraries_.pptx
PDF
Functions2.pdf
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PPTX
Chapter 2 Python Functions
PPTX
Functions in Python with all type of arguments
PDF
functions- best.pdf
PPTX
2 Functions2.pptx
PYTHON_FUNCTIONS in Detail user defined and Built In
Unit 1-Part-5-Functions and Set Operations.pdf
Functions in Python Programming Language
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
Lecture 08.pptx
Functions in python slide share
3-Python Functions.pdf in simple.........
functions.pptx
functioninpython-1.pptx
UNIT 3 python.pptx
Python for Data Science function third module ppt.pptx
 
_Python_ Functions _and_ Libraries_.pptx
Functions2.pdf
CHAPTER 01 FUNCTION in python class 12th.pptx
Chapter 2 Python Functions
Functions in Python with all type of arguments
functions- best.pdf
2 Functions2.pptx

More from Vinod Deenathayalan

PPT
python introduction to user friendly.ppt
PPTX
python for data anal gh i o fytysis creation.pptx
PPTX
data analytics ppt download for big data
PPTX
REVIEW OF PROJECT PRESENT PYTHON OK pptx
PPTX
ITPHP0 REVIEW OF THE PYTHON PROJECT Kpptx
PPTX
UNIT 2hidden surface elimination in graphics.pptx
PPTX
UNIT 1 2dviewing of image151213164537.pptx
PPT
Introduction to PHGGHython Programming.ppt
PPT
]animation of multimedia systems in the graphics.ppt
PPTX
data analytics for the cloud and big data
PPT
catering of the tamilnadu lifestyle hi cre
PPTX
introduction to multimedia system design.pptx
PPTX
smart-agriculture-system-using-iot-ppt.pptx
PPTX
UNIT 1 2D AND 3Dtransformations hiutu h.pptx
PPT
Unit-2 nano YYFYTFTF FYTFY YTRT6RTFJF.ppt
PPTX
Tools for Online Learning IN MACHINE LEARNING.pptx
PPTX
Tools for Online Learning IN EMBEDDED SYSTEMS.pptx
python introduction to user friendly.ppt
python for data anal gh i o fytysis creation.pptx
data analytics ppt download for big data
REVIEW OF PROJECT PRESENT PYTHON OK pptx
ITPHP0 REVIEW OF THE PYTHON PROJECT Kpptx
UNIT 2hidden surface elimination in graphics.pptx
UNIT 1 2dviewing of image151213164537.pptx
Introduction to PHGGHython Programming.ppt
]animation of multimedia systems in the graphics.ppt
data analytics for the cloud and big data
catering of the tamilnadu lifestyle hi cre
introduction to multimedia system design.pptx
smart-agriculture-system-using-iot-ppt.pptx
UNIT 1 2D AND 3Dtransformations hiutu h.pptx
Unit-2 nano YYFYTFTF FYTFY YTRT6RTFJF.ppt
Tools for Online Learning IN MACHINE LEARNING.pptx
Tools for Online Learning IN EMBEDDED SYSTEMS.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
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
PPTX
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
PDF
Introduction to MySQL Spatial Features and Real-World Use Cases
PPTX
Computer engineering for collage studen. pptx
PPTX
Washing-Machine-Simulation-using-PICSimLab.pptx
PPTX
Mc25104 - data structures and algorithms using PYTHON OOP_Python_Lecture_Note...
PPTX
clustering type :hierarchical clustering.pptx
PPTX
ensemble learning of machine learning .pptx
PDF
November_2025 Top 10 Read Articles in Computer Networks & Communications.pdf
PPTX
introduction-to-maintenance- Dr. Munthear Alqaderi
PPTX
Principles of Energy Efficiency_ Doing More with Less
PPTX
Lead-acid battery.pptx.........................
PDF
Grade 11 Quarter 3 Gravitational Potentional Energy
PPT
399-Cathodic-Protection-Presentation.ppt
 
PPTX
2-Photoelectric effect, phenomena and its related concept.pptx
PDF
HEV Descriptive Questions https://www.slideshare.net/slideshow/hybrid-electr...
PPTX
waste to energy deck v.3.pptx changing garbage to electricity
PPTX
Waste to Energy - G2 Ethanol.pptx to process
PRIZ Academy - Thinking The Skill Everyone Forgot
CEC369 IoT P CEC369 IoT P CEC369 IoT PCEC369 IoT PCEC369 IoT P
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
Introduction to MySQL Spatial Features and Real-World Use Cases
Computer engineering for collage studen. pptx
Washing-Machine-Simulation-using-PICSimLab.pptx
Mc25104 - data structures and algorithms using PYTHON OOP_Python_Lecture_Note...
clustering type :hierarchical clustering.pptx
ensemble learning of machine learning .pptx
November_2025 Top 10 Read Articles in Computer Networks & Communications.pdf
introduction-to-maintenance- Dr. Munthear Alqaderi
Principles of Energy Efficiency_ Doing More with Less
Lead-acid battery.pptx.........................
Grade 11 Quarter 3 Gravitational Potentional Energy
399-Cathodic-Protection-Presentation.ppt
 
2-Photoelectric effect, phenomena and its related concept.pptx
HEV Descriptive Questions https://www.slideshare.net/slideshow/hybrid-electr...
waste to energy deck v.3.pptx changing garbage to electricity
Waste to Energy - G2 Ethanol.pptx to process

python slides introduction interrupt.ppt

  • 1.
    14. Python -Functions• A function is a block of organized, reusable code that is used toperform a single, related action. Functions provides better modularityfor your application and a high degree of code reusing.• As you already know, Python gives you many built-in functions likeprint() etc. but you can also create your own functions. These functionsare called user-defined functions.
  • 2.
    Defining a FunctionHereare simple rules to define a function in Python:• Function blocks begin with the keyword def followed by the functionname and parentheses ( ( ) ).• Any input parameters or arguments should be placed within theseparentheses. You can also define parameters inside theseparentheses.• The first statement of a function can be an optional statement - thedocumentation string of the function or docstring.• The code block within every function starts with a colon (:) and isindented.• The statement return [expression] exits a function, optionally passingback an expression to the caller. A return statement with noarguments is the same as return None.• Syntax:• def functionname( parameters ):• "function_docstring" function_suite return [expression]
  • 3.
    • Syntax:def functionname(parameters ):"function_docstring"function_suitereturn [expression]By default, parameters have a positional behavior, and you needto inform them in the same order that they were defined.• Example:def printme( str ):"This prints a passed string function"print strreturn
  • 4.
    Calling a Function•Following is the example to call printme() function:def printme( str ): "This is a print function“print str;return;printme("I'm first call to user defined function!");printme("Again second call to the same function");• This would produce following result:I'm first call to user defined function!Again second call to the same function
  • 5.
    Pass by referencevs valueAll parameters (arguments) in the Python language are passed byreference. It means if you change what a parameter refers to within afunction, the change also reflects back in the calling function. Forexample:def changeme( mylist ): "This changes a passed list“mylist.append([1,2,3,4]);print "Values inside the function: ", mylistreturnmylist = [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]]
  • 6.
    There is onemore example where argument is being passed by reference butinside 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: ", mylistreturnmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist• The parameter mylist is local to the function changeme. Changing mylistwithin the function does not affect mylist. The function accomplishesnothing and finally this would produce following result:Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]
  • 7.
    Function Arguments:A functionby using the following types of formal arguments::– Required arguments– Keyword arguments– Default arguments– Variable-length argumentsRequired arguments:• Required arguments are the arguments passed to a function in correctpositional order.def printme( str ): "This prints a passed string"print str;return;printme();• This would produce following result:Traceback (most recent call last):File "test.py", line 11, in <module> printme();TypeError: printme() takes exactly 1 argument (0 given)
  • 8.
    Keyword arguments:• Keywordarguments are related to the function calls. When youuse keyword arguments in a function call, the caller identifiesthe arguments by the parameter name.• This allows you to skip arguments or place them out of orderbecause the Python interpreter is able to use the keywordsprovided to match the values with parameters.def printme( str ): "This prints a passed string"print str;return;printme( str = "My string");• This would produce following result:My string
  • 9.
    Following example givesmore clear picture. Note, here order ofthe 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
  • 10.
    Default arguments:• Adefault argument is an argument that assumes a defaultvalue if a value is not provided in the function call for thatargument.• Following example gives idea on default arguments, it wouldprint 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
  • 11.
    Variable-length arguments:• Youmay need to process a function for more arguments thanyou specified while defining the function. These arguments arecalled variable-length arguments and are not named in thefunction definition, unlike required and default arguments.• The general syntax for a function with non-keyword variablearguments is this:def functionname([formal_args,] *var_args_tuple ):"function_docstring"function_suitereturn [expression]
  • 12.
    • An asterisk(*) is placed before the variable name that will hold thevalues of all nonkeyword variable arguments. This tuple remainsempty if no additional arguments are specified during the functioncall. For example:def printinfo( arg1, *vartuple ):"This is test"print "Output is: "print arg1for var in vartuple:print varreturn;printinfo( 10 );printinfo( 70, 60, 50 );• This would produce following result:Output is:10Output is:706050
  • 13.
    The Anonymous Functions:Youcan use the lambda keyword to create small anonymous functions.These functions are called anonymous because they are not declaredin the standard manner by using the def keyword.• Lambda forms can take any number of arguments but return just onevalue in the form of an expression. They cannot contain commands ormultiple expressions.• An anonymous function cannot be a direct call to print becauselambda requires an expression.• Lambda functions have their own local namespace and cannot accessvariables other than those in their parameter list and those in theglobal namespace.• Although it appears that lambda's are a one-line version of a function,they are not equivalent to inline statements in C or C++, whosepurpose is by passing function stack allocation during invocation forperformance reasons.• Syntax:lambda [arg1 [,arg2,.....argn]]:expression
  • 14.
    Example:• Following isthe example to show how lembda form of functionworks:sum = lambda arg1, arg2: arg1 + arg2;print "Value of total : ", sum( 10, 20 )print "Value of total : ", sum( 20, 20 )• This would produce following result:Value of total : 30Value of total : 40
  • 15.
    Scope of Variables:•All variables in a program may not be accessible at all locations in thatprogram. This depends on where you have declared a variable.• The scope of a variable determines the portion of the program whereyou can access a particular identifier. There are two basic scopes ofvariables in Python:Global variablesLocal 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 thefunction in which they are declared whereas global variables can beaccessed throughout the program body by all functions. When you calla function, the variables declared inside it are brought into scope.
  • 16.
    • Example:total =0; # This is global variable.def sum( arg1, arg2 ):"Add both the parameters"total = arg1 + arg2;print "Inside the function local total : ", totalreturn total;# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total• This would produce following result:Inside the function local total : 30Outside the function global total : 0

[8]ページ先頭

©2009-2025 Movatter.jp