Page 130 - 2620_Birla Open Mind C-8
P. 130

Creating a Function

              We can create a function in the following ways:

                  Defining a Function: We use the def keyword to begin the function definition.

                  Naming a Function: Provide a meaningful name to your function.

                  Parameters: These are the variables given inside the parentheses in the function definition. The
                 parameters (separated by commas) are given in the parentheses following the name of the function.

                  Body of the Function: The body of the function contains Python statements that perform the task
                 or computation for which function is designed for.

              Syntax of creating a function is:

                 def < name of the function > (list of parameters):

                     <body of a function >

              Calling a Function

              A function can be called anytime from other functions or from the command prompt after the definition.
              For calling a function, we type the function name followed by parentheses containing any required
              parameters. For example:

              To call a function


                                def my_function():                                  Name of a function
                                      print ("Hello")                               Body of a function

                                my_function()                                       Function call


              Program 1: To print a string by calling a function

                   Program1.py
               File  Edit  Format    Run   Options   Window    Help

                #Function definition


                def hello (name):
                    print('Hello ' +name+ '! How do you do?')

                #Calling function by passing parameter
                hello('Orange')



              You will get the following output:
                   Output

                Hello Orange! How do you do?






                  128  Premium Edition-VIII
   125   126   127   128   129   130   131   132   133   134   135