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

More Related Content

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

Similar to JNTUK python programming python unit 3.pptx

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

More from Venkateswara Babu Ravipati

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

Recently uploaded

PPTX
clustering type :hierarchical clustering.pptx
PDF
PRIZ Academy - Thinking The Skill Everyone Forgot
PPTX
Push pop Unit 1 CEC369 IoT P CEC369 IoT P
PDF
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
PDF
k-means algorithm with numerical solution.pdf
PPT
Virtual Instrumentation Programming Techniques.ppt
PPTX
Mc25104 - data structures and algorithms using PYTHON OOP_Python_Lecture_Note...
PPTX
ensemble learning of machine learning .pptx
PDF
Small Space Big Design - Amar DeXign Scape
PDF
@Regenerative braking system of DC motor
PPTX
Ship Repair and fault diagnosis and restoration of system back to normal .pptx
PPTX
AI at the Crossroads_ Transforming the Future of Green Technology.pptx
PDF
Reinforced Earth Walls Notes .pdf
PDF
Welcome to ISPR 2026 - 12th International Conference on Image and Signal Pro...
PPTX
Supercapacitor.pptx...............................
PPTX
2-Photoelectric effect, phenomena and its related concept.pptx
PPTX
Intrusion Detection Systems presentation.pptx
PPTX
Lead-acid battery.pptx.........................
PPTX
waste to energy deck v.3.pptx changing garbage to electricity
PPTX
Waste to Energy - G2 Ethanol.pptx to process
clustering type :hierarchical clustering.pptx
PRIZ Academy - Thinking The Skill Everyone Forgot
Push pop Unit 1 CEC369 IoT P CEC369 IoT P
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
k-means algorithm with numerical solution.pdf
Virtual Instrumentation Programming Techniques.ppt
Mc25104 - data structures and algorithms using PYTHON OOP_Python_Lecture_Note...
ensemble learning of machine learning .pptx
Small Space Big Design - Amar DeXign Scape
@Regenerative braking system of DC motor
Ship Repair and fault diagnosis and restoration of system back to normal .pptx
AI at the Crossroads_ Transforming the Future of Green Technology.pptx
Reinforced Earth Walls Notes .pdf
Welcome to ISPR 2026 - 12th International Conference on Image and Signal Pro...
Supercapacitor.pptx...............................
2-Photoelectric effect, phenomena and its related concept.pptx
Intrusion Detection Systems presentation.pptx
Lead-acid battery.pptx.........................
waste to energy deck v.3.pptx changing garbage to electricity
Waste to Energy - G2 Ethanol.pptx to process

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