Page 105 - Computer - 8
P. 105

User-defined functions in Python can be of three forms:

             •   User-defined  functions  without  parameters  and  not  returning  any  value:  These  functions
                neither take any input values nor return any output. The function contains any input and output
                operations inside the body of the function.
             •   User-defined  functions  with  parameters  and  not  returning  any  value:  These  functions  take
                one or more input values but do not return any output. The function contains input and output
                operation statements but not the final output. It may be displayed inside the function itself.

             •  User-defined functions with parameters and returning a value: These functions take one or more
                input values and also return some output. The function contains input and output operation
                statements and returns the final output. The returned value can be used in another function or
                stored in a variable.

          CREATING A FUNCTION

          Python provides the def keyword to create a user-defined function. The syntax to create a function is:
                 def <function name>(arguments list):

                        body of function

                        return <expression>
          Here, def is the keyword which tells the interpreter that a function is being defined.

                function name is the name of the user-defined function. It follows the same rules as used for
                naming a variable in Python.
                arguments list contains all the values given to the function as input. The arguments can be a
                value, a variable, or an expression. In case of more than one arguments passed to the function, they
                are separated by commas ( , ).

                body of function contains all the executable statements required by the function.
                return statement specifies the value returned by the function as output.


          CALLING A FUNCTION
          The process of using a function at the Python prompt or in a program is known as Calling the function.
          While calling a function, we must use its correct name and pass the required number of arguments to
          it. If the function returns a value, care must be taken to store the value in a variable.

          For example, the statement to call the area_square function as described earlier in the chapter is

                 SqArea = area_square(20), or
                 >>> print(area_square(10))




          Mind Fog       ERROR


             The calling statement for a function cannot be placed before defining the function.



                                                                                                             103
   100   101   102   103   104   105   106   107   108   109   110