40 likes | 158 Vues
In Python, function parameters are passed by value, meaning the function receives a copy of the argument's value. When a parameter is modified within a function, the change does not affect the original argument used in the call. For example, if you set a parameter to a new value in a function, that value will only persist within the function's scope and will revert once the function exits. To make permanent changes, you should use a return statement to send back modified values to the calling code. Remember, passing by reference is another method, encountering lists later might explain its mechanics.
E N D
Can a function change a parameter permanently? • Given this little function • def fun1 (a): a = 15 • Does it change its parameter inside the function? Yes. After that statement, a would be 15. How long would a be 15? Until it was changed again or until the function ended • Does it change the argumentwhich was used to call the function, that matched the parameter? No, it does not.
Passing by value • In Python the default way that arguments are passed to become parameters in a function is by value. • That means that the function gets a copy of the argument’s value for the parameter to use. Whatever happens to the parameter in the function has NO effect on the argument in the calling code. • Making permanent changes is what the return statement is for. • You use the return statement to send back values to the calling code.
Why? • Why discuss this? This is described in the other examples of functions • Python and other languages have another way to pass arguments to parameters which does allow for a permanent change • This way is called passing by reference • We will see this later when we get into lists. For now, just remember that passing by value is the default way and it means that functions do NOT make permanent changes to their parameters.