Movatterモバイル変換


[0]ホーム

URL:


PPTX, PDF55 views

JNTUK python programming python unit 3.pptx

The document provides a comprehensive overview of Python functions, highlighting their purpose in code reusability and debugging. It covers various types of arguments like required, keyword, default, and variable-length arguments, along with the use of lambda functions and the concept of local versus global variables. The document concludes with examples illustrating the scope of variables and the differences between pass-by-reference and pass-by-value.

Embed presentation

Download to read offline
Presented byV Babu RavipatiUnit -3
2Functions1. Reusability2. Easy debugging
14. Python - FunctionsA 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 highdegree of code reusing.As you already know, Python gives you many built-in functions like print() etc. but youcan also create your own functions. These functions are 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 thefunction name (shouldnot be keyword) and parentheses ( ) .• Any input parameters or arguments should be placed withinthese parentheses. You can also define parameters orarguments 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 (:) andis indented.• The statement return [expression] exits a function, optionallypassing back an expression to the caller. A return statementwith no arguments is the same as return None.
Syntax:def functionname( parameters ):"function_docstring“function_suite[expression]returnExampleDef add(a,b):sum=a+breturn suma=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 argumentsRequired 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: RamuAge 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 parametername.• This allows you to skip arguments or place them outof order because the Python interpreter is able touse the keywords provided to match the values withparameters.
Following example gives more clear picture. Note, here order of the parameterdoes not matter:def printinfo( name, age ): "Test function"print ("Name: ", name)print ("Age ", age)returnprintinfo(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 isnot provided in the function call for that argument.Following example gives idea on default arguments, it would print default ageif it is not passed:def printinfo( name, age = 35 ): “Test function"print ("Name: ", name)print ("Age ", age)returnprintinfo( 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 specifiedwhile defining the function. These arguments are called variable-lengtharguments and are not named in the function definition, unlike required anddefault arguments.The general syntax for a function with non-keyword variable arguments 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 the values ofall nonkeyword variable arguments. This tuple remains empty if no additionalarguments 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 varreturnprintinfo( 10 )printinfo( 70, 60, 50 )This would produce following result:Output is:10Output is:706050
Lambda FunctionLambda functions are also called anonymousfunctions. An anonymous function is afunction defined without a name. As weknow to define a normal function in python,we need to use the def keyword. But in thiscase of anonymous functions, we use thelambda keyword to define the functions.
The characteristics of lambda function• The lambda function can take manyarguments but can return only one expression.• Syntactically, lambda functions are restrictedto only a single expression.• We can use them as an anonymous functioninside other functions.• Lambda function is reusable.
Why should we use lambda functions?Lambda functions are used when weneed a function for a short period oftime. This is commonly used when wewant to pass a function as an argumentto higher-order functions, that is,functions that take other functions astheir arguments
Why should we use lambda functions?
Example
17Fruitful FunctionsProperties of Fruitful functions are1. Return Value2. Incremental Development3. Composition4. Boolean type
1.Return Valuedef sum()a=10b=15c=a+bprint(c)Sum()def sum(a,b)c=a+breturn cPrint(sum(10,15))
def area(radius):temp = 3.14159 * radius**2return tempdef area(radius):return 3.14159 * radius**2Sometimes it is useful to have multiple return statements, one in each branch of aconditional.def absolute_value(x):if x < 0:return -xelse:return x
2.Incremental developmentTo deal with increasingly complex programs, we aregoing to suggest a technique called incrementaldevelopment. The goal of incremental development is toavoid long debugging sessions by adding and testingonly a small amount of code at a time.As an example, suppose you want to find the distancebetween two points, given by the coordinates (x1, y1)and (x2, y2). By the Pythagorean theorem, the distanceis:
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 - x1dy = y2 - y1print 'dx is ', dxprint 'dy is ', dyreturn 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 - y1result =(dx**2 + dy**2)**0.5return 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.5return 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 smallincremental changes. At any point, if there is an error,you will know exactly where it is.2. Use temporary variables to hold intermediate valuesso you can output and check them.3. Once the program is working, you might want toremove some of the scaffolding or consolidatemultiple statements into compound expressions, butonly if it does not make the program difficult to read.
3.CompositionAs you should expect by now, you can call one functionfrom within another. This ability is called composition.def area2(xc, yc, xp, yp):radius = distance(xc, yc, xp, yp)result = area(radius)return resultdef area2(xc, yc, xp, yp):return area(distance(xc, yc, xp, yp))
4.Creating Boolean functionsFunctions that return a Boolean value(True or False) can be used inconditional statements (i.e. if…else…)05/02/09Python Mini-Course: Day 2 - Lesson 828
is_divisible functiondef is_divisible(x, y):if x % y == 0:return Trueelse:return Falseis_divisible(16,4)is_divisible(16,3)05/02/09Python Mini-Course: Day 2 - Lesson 829
Scope of Variables:All variables in a program may not be accessible at all locations in that program. Thisdepends on where you have declared a variable.The scope of a variable determines the portion of the program where you can access aparticular identifier. There are two basic scopes of variables in Python:Global variablesLocal variablesGlobal vs. Local variables:Variables that are defined inside a function body have a local scope, and those definedoutside have a global scope.This means that local variables can be accessed only inside the function in which theyare declared whereas global variables can be accessed throughout the program body byall functions. When you call a function, the variables declared inside it are brought intoscope.
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 : ", totalThis would produce following result:Inside the function local total : 30Outside the function global total : 0
There is one more example where argument is being passed by reference but inside thefunction, 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)returnmylist = [10,20,30];changeme( mylist );Print("Values outside the function: ", mylist)The parameter mylist is local to the function changeme. Changing mylist within the functiondoes not affect mylist. The function accomplishes nothing and finally this would producefollowing result:Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]
Pass by reference vs valueAll parameters (arguments) in the Python language are passed by reference. It means ifyou change what a parameter refers to within a function, the change also reflects backin 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)returnmylist = [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

Recommended

PPTX
Python Functions.pptx
PPT
functions _
PPT
Powerpoint presentation for Python Functions
PPT
python slides introduction interrupt.ppt
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPT
Python programming variables and comment
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PPT
functions modules and exceptions handlings.ppt
PDF
3-Python Functions.pdf in simple.........
PPTX
UNIT 3 python.pptx
PDF
Functions2.pdf
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PDF
functions- best.pdf
PPTX
Functions in Python Programming Language
PPTX
functions.pptx
PPTX
functioninpython-1.pptx
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPTX
Python programming - Functions and list and tuples
PDF
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
PPTX
FUNCTIONS.pptx
PDF
functions notes.pdf python functions and opp
PPTX
Functions and Modules.pptx
PPTX
PPT JNTUK python programming unit 2.pptx
PPTX
EG-Unit-2- Points.pptx

More Related Content

PPTX
Python Functions.pptx
PPT
functions _
PPT
Powerpoint presentation for Python Functions
PPT
python slides introduction interrupt.ppt
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPT
Python programming variables and comment
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
Python Functions.pptx
functions _
Powerpoint presentation for Python Functions
python slides introduction interrupt.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Python programming variables and comment
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PYTHON_FUNCTIONS in Detail user defined and Built In

Similar to JNTUK python programming python unit 3.pptx

PPT
functions modules and exceptions handlings.ppt
PDF
3-Python Functions.pdf in simple.........
PPTX
UNIT 3 python.pptx
PDF
Functions2.pdf
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PDF
functions- best.pdf
PPTX
Functions in Python Programming Language
PPTX
functions.pptx
PPTX
functioninpython-1.pptx
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPTX
Python programming - Functions and list and tuples
PDF
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
PPTX
FUNCTIONS.pptx
PDF
functions notes.pdf python functions and opp
PPTX
Functions and Modules.pptx
functions modules and exceptions handlings.ppt
3-Python Functions.pdf in simple.........
UNIT 3 python.pptx
Functions2.pdf
cbse class 12 Python Functions2 for class 12 .pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
functions- best.pdf
Functions in Python Programming Language
functions.pptx
functioninpython-1.pptx
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Python programming - Functions and list and tuples
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
Python for Data Science function third module ppt.pptx
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
FUNCTIONS.pptx
functions notes.pdf python functions and opp
Functions and Modules.pptx

More from Venkateswara Babu Ravipati

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

Recently uploaded

PPTX
2-Photoelectric effect, phenomena and its related concept.pptx
PDF
222109_MD_MILTON_HOSSAIN_26TH_BATCH_REGULAR_PMIT V5.pdf
PPTX
Intrusion Detection Systems presentation.pptx
PPTX
Ship Repair and fault diagnosis and restoration of system back to normal .pptx
PDF
IPE 105 - Engineering Materials Constitution of Alloys
PDF
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
PDF
Stern-Gerlach-Experiment from quantum mechanics
PPTX
K-nearest neighbouring machine learing algorithm .pptx
PDF
ANPARA THERMAL POWER STATION[1] sangam.pdf
PPTX
Washing-Machine-Simulation-using-PICSimLab.pptx
PPTX
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
PDF
@Regenerative braking system of DC motor
PDF
application of matrix in computer science
PPTX
CEC369 IoT P CEC369 IoT P CEC369 IoT PCEC369 IoT PCEC369 IoT P
PPTX
ensemble learning of machine learning .pptx
PPTX
DevFest Seattle 2025 - AI Native Design Patterns.pptx
PPTX
Principles of Energy Efficiency_ Doing More with Less
PDF
Introduction to MySQL Spatial Features and Real-World Use Cases
PPT
Virtual Instrumentation Programming Techniques.ppt
PPTX
TRANSPORTATION ENGINEERING Unit-5.1.pptx
2-Photoelectric effect, phenomena and its related concept.pptx
222109_MD_MILTON_HOSSAIN_26TH_BATCH_REGULAR_PMIT V5.pdf
Intrusion Detection Systems presentation.pptx
Ship Repair and fault diagnosis and restoration of system back to normal .pptx
IPE 105 - Engineering Materials Constitution of Alloys
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
Stern-Gerlach-Experiment from quantum mechanics
K-nearest neighbouring machine learing algorithm .pptx
ANPARA THERMAL POWER STATION[1] sangam.pdf
Washing-Machine-Simulation-using-PICSimLab.pptx
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
@Regenerative braking system of DC motor
application of matrix in computer science
CEC369 IoT P CEC369 IoT P CEC369 IoT PCEC369 IoT PCEC369 IoT P
ensemble learning of machine learning .pptx
DevFest Seattle 2025 - AI Native Design Patterns.pptx
Principles of Energy Efficiency_ Doing More with Less
Introduction to MySQL Spatial Features and Real-World Use Cases
Virtual Instrumentation Programming Techniques.ppt
TRANSPORTATION ENGINEERING Unit-5.1.pptx

JNTUK python programming python unit 3.pptx

  • 1.
    Presented byV BabuRavipatiUnit -3
  • 2.
  • 3.
    14. Python -FunctionsA 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 highdegree of code reusing.As you already know, Python gives you many built-in functions like print() etc. but youcan also create your own functions. These functions are called user-defined functions.
  • 4.
    Defining a FunctionHereare simple rules to define a function in Python:• Function blocks begin with the keyword def followed by thefunction name (shouldnot be keyword) and parentheses ( ) .• Any input parameters or arguments should be placed withinthese parentheses. You can also define parameters orarguments 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 (:) andis indented.• The statement return [expression] exits a function, optionallypassing back an expression to the caller. A return statementwith no arguments is the same as return None.
  • 5.
    Syntax:def functionname( parameters):"function_docstring“function_suite[expression]returnExampleDef add(a,b):sum=a+breturn suma=int(input(“enter first number”))b=int(input(“enter second number”))res=add(a,b)print(“result = “res)
  • 6.
    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 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: RamuAge 29
  • 7.
    Keyword arguments:• Keywordarguments are related to the function calls.When you use keyword arguments in a function call,the caller identifies the arguments by the parametername.• This allows you to skip arguments or place them outof order because the Python interpreter is able touse the keywords provided to match the values withparameters.
  • 8.
    Following example givesmore clear picture. Note, here order of the parameterdoes not matter:def printinfo( name, age ): "Test function"print ("Name: ", name)print ("Age ", age)returnprintinfo(age=50, name="miki" )This would produce following result:Name: miki Age 50
  • 9.
    Default arguments:A defaultargument is an argument that assumes a default value if a value isnot provided in the function call for that argument.Following example gives idea on default arguments, it would print default ageif it is not passed:def printinfo( name, age = 35 ): “Test function"print ("Name: ", name)print ("Age ", age)returnprintinfo( 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 mayneed to process a function for more arguments than you specifiedwhile defining the function. These arguments are called variable-lengtharguments and are not named in the function definition, unlike required anddefault arguments.The general syntax for a function with non-keyword variable arguments is this:def functionname([formal_args,] *var_args_tuple ):"function_docstring"function_suitereturn [expression]
  • 11.
    An asterisk (*)is placed before the variable name that will hold the values ofall nonkeyword variable arguments. This tuple remains empty if no additionalarguments 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 varreturnprintinfo( 10 )printinfo( 70, 60, 50 )This would produce following result:Output is:10Output is:706050
  • 12.
    Lambda FunctionLambda functionsare also called anonymousfunctions. An anonymous function is afunction defined without a name. As weknow to define a normal function in python,we need to use the def keyword. But in thiscase of anonymous functions, we use thelambda keyword to define the functions.
  • 13.
    The characteristics oflambda function• The lambda function can take manyarguments but can return only one expression.• Syntactically, lambda functions are restrictedto only a single expression.• We can use them as an anonymous functioninside other functions.• Lambda function is reusable.
  • 14.
    Why should weuse lambda functions?Lambda functions are used when weneed a function for a short period oftime. This is commonly used when wewant to pass a function as an argumentto higher-order functions, that is,functions that take other functions astheir arguments
  • 15.
    Why should weuse lambda functions?
  • 16.
  • 17.
    17Fruitful FunctionsProperties ofFruitful functions are1. Return Value2. Incremental Development3. Composition4. Boolean type
  • 18.
    1.Return Valuedef sum()a=10b=15c=a+bprint(c)Sum()defsum(a,b)c=a+breturn cPrint(sum(10,15))
  • 19.
    def area(radius):temp =3.14159 * radius**2return tempdef area(radius):return 3.14159 * radius**2Sometimes it is useful to have multiple return statements, one in each branch of aconditional.def absolute_value(x):if x < 0:return -xelse:return x
  • 20.
    2.Incremental developmentTo dealwith increasingly complex programs, we aregoing to suggest a technique called incrementaldevelopment. The goal of incremental development is toavoid long debugging sessions by adding and testingonly a small amount of code at a time.As an example, suppose you want to find the distancebetween two points, given by the coordinates (x1, y1)and (x2, y2). By the Pythagorean theorem, the distanceis:
  • 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 - x1dy = y2 - y1print 'dx is ', dxprint 'dy is ', dyreturn 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 - y1result =(dx**2 + dy**2)**0.5return 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.5return 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 aspectsof the process are:1. Start with a working program and make smallincremental changes. At any point, if there is an error,you will know exactly where it is.2. Use temporary variables to hold intermediate valuesso you can output and check them.3. Once the program is working, you might want toremove some of the scaffolding or consolidatemultiple statements into compound expressions, butonly if it does not make the program difficult to read.
  • 27.
    3.CompositionAs you shouldexpect by now, you can call one functionfrom within another. This ability is called composition.def area2(xc, yc, xp, yp):radius = distance(xc, yc, xp, yp)result = area(radius)return resultdef area2(xc, yc, xp, yp):return area(distance(xc, yc, xp, yp))
  • 28.
    4.Creating Boolean functionsFunctionsthat return a Boolean value(True or False) can be used inconditional statements (i.e. if…else…)05/02/09Python Mini-Course: Day 2 - Lesson 828
  • 29.
    is_divisible functiondef is_divisible(x,y):if x % y == 0:return Trueelse:return Falseis_divisible(16,4)is_divisible(16,3)05/02/09Python Mini-Course: Day 2 - Lesson 829
  • 30.
    Scope of Variables:Allvariables in a program may not be accessible at all locations in that program. Thisdepends on where you have declared a variable.The scope of a variable determines the portion of the program where you can access aparticular identifier. There are two basic scopes of variables in Python:Global variablesLocal variablesGlobal vs. Local variables:Variables that are defined inside a function body have a local scope, and those definedoutside have a global scope.This means that local variables can be accessed only inside the function in which theyare declared whereas global variables can be accessed throughout the program body byall functions. When you call a function, the variables declared inside it are brought intoscope.
  • 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 : ", totalreturn total;# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", totalThis would produce following result:Inside the function local total : 30Outside the function global total : 0
  • 32.
    There is onemore example where argument is being passed by reference but inside thefunction, 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)returnmylist = [10,20,30];changeme( mylist );Print("Values outside the function: ", mylist)The parameter mylist is local to the function changeme. Changing mylist within the functiondoes not affect mylist. The function accomplishes nothing and finally this would producefollowing result:Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]
  • 33.
    Pass by referencevs valueAll parameters (arguments) in the Python language are passed by reference. It means ifyou change what a parameter refers to within a function, the change also reflects backin 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)returnmylist = [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]]
  • 34.

[8]ページ先頭

©2009-2025 Movatter.jp