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
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPT
Python programming variables and comment
PPT
functions modules and exceptions handlings.ppt
PPTX
Python programming - Functions and list and tuples
PPTX
Python Functions.pptx
PPT
functions _
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPTX
JNTUK python programming python unit 3.pptx
PPTX
Lecture 08.pptx
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PPTX
UNIT 3 python.pptx
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PDF
functions- best.pdf
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
2 Functions2.pptx
PDF
Unit 1-Part-5-Functions and Set Operations.pdf
PPTX
Functions in Python Programming Language
PPTX
Functions in Python with all type of arguments
PDF
3-Python Functions.pdf in simple.........
PPTX
Chapter 2 Python Functions
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PPTX
Functions in python slide share
PDF
Functions2.pdf
PPTX
functions.pptx
PPTX
functioninpython-1.pptx
PPTX
_Python_ Functions _and_ Libraries_.pptx
PPT
Introduction to PHGGHython Programming.ppt
PPTX
REVIEW OF PROJECT PRESENT PYTHON OK pptx

More Related Content

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

Similar to python slides introduction interrupt.ppt

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

More from Vinod Deenathayalan

PPT
Introduction to PHGGHython Programming.ppt
PPTX
REVIEW OF PROJECT PRESENT PYTHON OK pptx
PPTX
ITPHP0 REVIEW OF THE PYTHON PROJECT Kpptx
PPTX
data analytics for the cloud and big data
PPTX
data analytics ppt download for big data
PPT
catering of the tamilnadu lifestyle hi cre
PPTX
UNIT 1 2dviewing of image151213164537.pptx
PPTX
UNIT 2hidden surface elimination in graphics.pptx
PPTX
Tools for Online Learning IN EMBEDDED SYSTEMS.pptx
PPTX
Tools for Online Learning IN MACHINE LEARNING.pptx
PPT
]animation of multimedia systems in the graphics.ppt
PPTX
UNIT 1 2D AND 3Dtransformations hiutu h.pptx
PPTX
introduction to multimedia system design.pptx
PPTX
python for data anal gh i o fytysis creation.pptx
PPT
python introduction to user friendly.ppt
PPTX
smart-agriculture-system-using-iot-ppt.pptx
PPT
Unit-2 nano YYFYTFTF FYTFY YTRT6RTFJF.ppt
Introduction to PHGGHython Programming.ppt
REVIEW OF PROJECT PRESENT PYTHON OK pptx
ITPHP0 REVIEW OF THE PYTHON PROJECT Kpptx
data analytics for the cloud and big data
data analytics ppt download for big data
catering of the tamilnadu lifestyle hi cre
UNIT 1 2dviewing of image151213164537.pptx
UNIT 2hidden surface elimination in graphics.pptx
Tools for Online Learning IN EMBEDDED SYSTEMS.pptx
Tools for Online Learning IN MACHINE LEARNING.pptx
]animation of multimedia systems in the graphics.ppt
UNIT 1 2D AND 3Dtransformations hiutu h.pptx
introduction to multimedia system design.pptx
python for data anal gh i o fytysis creation.pptx
python introduction to user friendly.ppt
smart-agriculture-system-using-iot-ppt.pptx
Unit-2 nano YYFYTFTF FYTFY YTRT6RTFJF.ppt

Recently uploaded

PPT
lec13.ppt FOR COMPOSITES AND POLYMERS MATERIAL SCIENCE
PPTX
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
PPTX
Washing-Machine-Simulation-using-PICSimLab.pptx
PDF
Soil Permeability and Seepage-Irrigation Structures
PDF
Advancements in Telecommunication for Disaster Management (www.kiu.ac.ug)
PPTX
Waste to Energy - G2 Ethanol.pptx to process
PDF
Why Buildings Crumble Before Their Time And How We Can Build a Legacy
PDF
Stern-Gerlach-Experiment from quantum mechanics
PPTX
Computer engineering for collage studen. pptx
PDF
November_2025 Top 10 Read Articles in Computer Networks & Communications.pdf
PPTX
waste to energy deck v.3.pptx changing garbage to electricity
PPTX
Blockchain and cryptography Lecture Notes
PDF
OOPCodesjavapracticalkabirpawarpptinparacticalexamination
PPTX
Lead-acid battery.pptx.........................
PPTX
AI at the Crossroads_ Transforming the Future of Green Technology.pptx
PPTX
Supercapacitor.pptx...............................
PPTX
Intrusion Detection Systems presentation.pptx
PPTX
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
PPTX
DevFest Seattle 2025 - AI Native Design Patterns.pptx
PPTX
clustering type :hierarchical clustering.pptx
lec13.ppt FOR COMPOSITES AND POLYMERS MATERIAL SCIENCE
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
Washing-Machine-Simulation-using-PICSimLab.pptx
Soil Permeability and Seepage-Irrigation Structures
Advancements in Telecommunication for Disaster Management (www.kiu.ac.ug)
Waste to Energy - G2 Ethanol.pptx to process
Why Buildings Crumble Before Their Time And How We Can Build a Legacy
Stern-Gerlach-Experiment from quantum mechanics
Computer engineering for collage studen. pptx
November_2025 Top 10 Read Articles in Computer Networks & Communications.pdf
waste to energy deck v.3.pptx changing garbage to electricity
Blockchain and cryptography Lecture Notes
OOPCodesjavapracticalkabirpawarpptinparacticalexamination
Lead-acid battery.pptx.........................
AI at the Crossroads_ Transforming the Future of Green Technology.pptx
Supercapacitor.pptx...............................
Intrusion Detection Systems presentation.pptx
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
DevFest Seattle 2025 - AI Native Design Patterns.pptx
clustering type :hierarchical clustering.pptx

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