Describe functions in Python

Python Functions :
  • A function is a block of organized, reusable code that is used to perform a single, related action.
  • Python gives us many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
  • Parameter Passing :
    • We can pass arguments to a function either by value or by reference.
    • Call by Value :
      • Sometimes it's also called pass by value.
      • In call-by-value, the argument expression is evaluated, and the result of this evaluation is bound to the corresponding variable in the function. So, if the expression is a variable, a local copy of its value will be used, i.e. the variable in the caller's scope will be unchanged when the function returns.
    • Call by Reference :
      • It is also known as pass-by-reference.
      • In this a function gets an implicit reference to the argument, rather than a copy of its value.
      • As a consequence, the function can modify the argument, i.e. the value of the variable in the caller's scope can be changed.
      • The function can modify the argument, i.e. the value of the variable in the caller's scope can be changed.
      • The disadvantage of it is that variables can be "accidentally" changed in a function call. So special care has to be taken to "protect" the values, which shouldn't be changed. 
  • What is used in Python?
    • Python uses a mechanism, which is known as "Call-by-Object", sometimes also called "Call by Object Reference" or "Call by Sharing".
    • If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e. they are immutable.
    • It's different, if we pass mutable arguments. They are also passed by object reference, but they can be changed in place in the function. If we pass a list to a function, we have to consider two cases: Elements of a list can be changed in place, i.e. the list will be changed even in the caller's scope. If a new list is assigned to the name, the old list will not be affected, i.e. the list in the caller's scope will remain untouched.

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?