Tuesday, December 1, 2020

Calling a Function in Python

 Calling a Function in Python

* A function does not have the power to run on its own

* A function can run only when called by an external calling function

* So after a function has been created in Python , it can only be called later by the help of another function or object by using a name

* While calling a function , one should pass necessary values to the function within the parenthesis in the form :

sum(10,15)

* In the above calling function 'sum'  two values are passed to the calling function whose name is sum and the value arguments passed into the sum function are 10 and 20

* When this statement is executed , the Python interpreter jumps into the function definition where the function sum had been declared with the constituting parameter values which are 10 and 20 into the parameters 'a' and 'b' respectively

* These values are processed within a function body and the corresponding result is obtained for the same 

* These values passed to a function are called as 'arguments'


Program

A function that accepts two values and finds their sum has been provided below .

# a function to add two numbers

def sum(a , b):

    "" this function finds the sum of two numbers ""

    c = a + b

    print('Sum=',c)

    # calling the function

    sum(10,20)

    sum(30,40)


Output

Sum = 30

Sum = 70


In the program , the user of the program is calling the sum() function two times and after the call of the function the output pertaining to each of the called function's statement is obtained as output .

Once a function has been created , the function can be used again and again whenever the need to call that function arises and by this process the functions are made to be reusable and thus are utilised as a set of reusable function or reusable code within a body of bigger code (Project).

One may note from the above discussion , that while the function has been called , an integer type data is passed into the function . But for this type of function , one can pass float type data to the function as well whenever the function gets called at any point of time .

No comments:

Post a Comment