Yesterday in Python A passer-by in the study group asked Python A basic problem about formal parameter and real parameter in function , Although very basic , But for a lot of Xiaobai, it's not necessarily simple , On the contrary, they will be confused . Life is too short , I use Python.
In order to answer this question , Xiao Bian gives a chestnut here , I hope you can thoroughly understand that arguments and formal parameters are Python In the middle of the day .
First , Let's see a chestnut .
Unchangeable objects
What is the output value of this function ? A lot of people will answer 7, Actually, after the program runs , The answer is 6, What about the solution ?
Why does the value of a formal parameter not change the value of an actual parameter here ?
Here we need to popularize a Python Foundation in , stay python in ,string( character string ), tuples( Tuples ), and number( The number ) Is an object that cannot be changed , and list( list ),dict( Dictionaries ) And so on are modifiable objects .
in other words , Here, the value of the formal parameter is the value of the external argument (number type , immutable ) It has nothing to do with , Although they have the same name , But the object it points to is different . So when printing at the end of the program a When outputting values , The output is still 6.
Let's take a look at the variable objects , With list( list ) As an experimental object .
Changeable objects
What is the output value of this function ? A lot of people will answer [1,2], Actually, after the program runs , The answer is [2,1].
Just the opposite of the first chestnut , Here, the numeric call of formal parameter changes the actual parameter . Because in this case, the parameter passes a list , It is a changeable object , After a series of assignment changes inside the function , So the output value of the program changes after it runs .
Mountains and rivers lead nowhere , Another village . This question is often used as an interview question by recruitment companies and enterprises , Investigate the interview dog Python Basic knowledge of , I hope you will take a good look at , Pay attention to similar problems in the future , Little detours !
Thank you Python Good scholars who actively ask questions in the group , But we all work together to learn Python And fight ! Finally, I wish you all a happy Valentine's Day ~~~