In Python, a function is a group of related statements that performs a specific task, calculations. There were several built in functions like sqrt(), power() ..in python to perform various tasks.
However, we can create our own functions called 'user defined' functions. Once a Function is defined, it can be re-usable whenever needed required, which avoid redundancy.
The Functions provide modularity for a Programming. A module represents part of the program.
Generally, in programming, we divide the main task into a smaller sub tasks called Modules.
To represent each module, we can develop a function, which makes the programming simple.
We can define a function with the keyword "def " and function name with parenthesis(), which may contains the arguments as well.
Syntax :
def functionname ( arg1, arg2..argn) :
""" function docstring """
function statements
Example :
def addnum(a, b):
""" This function adds two numbers """ c = a+b
return c
Notes:
In the above example, the parameters a, b do not know which type of value they are going to receive, till values are passed at the time of calling function. During run time a, b may assume any type of data, may be int or float or strings. This is called 'dynamic typing', where the type of data is determined only during runtime not at compile time. This dynamic typing is one of the features of Python.
A function is called using its name. When a function is written inside a Class, its becomes a Method. A method can be using the following ways.
objectname.methodname()
Classname.methodname()
A function cannot run on its own. It runs only when we call it.
x = addnum(10, 15)
print('The sum is:', x)
# Result:
The sum is: 25
# ------------------------------------------------------------------------------------------------------------------------ #
The docstrings will provide a summary of what that function or method will do. It is a good practice to main doc strings in the programming.
# ------------------------------------------------------------------------------------------------------------------------ #
Returning multiple values from a Function:
In Python, we can use the function to perform multiple calculation and return multiple values as well. The returns statement is as:
return a, b, c
Example1 :
def add_sub(a, b):
c = a + b
d = a - b
return c, d
Since this function has two parameters, we should pass two values as:
x, y = add_sum(10, 15)
The result of addition in c will be stored into x and the result of subtraction in d will be stored into y.
Now lets create the above function with more detailed way for better understanding.
# Function to calculate addition and subtraction two numbers
def add_sub(a, b):
""" This function returns the results of addition and subtraction of the two numbers """
c = a + b
d = a - b
return c, d
# get the results from the above function
x, y = add_sub(10, 5)
# print the results from the above function
print('The result of addition is: ', x)
print('The result of subtraction is: ', y)
#Result:
The result of addition is: 15
The result of subtraction is: 5
Example 2:
# Function to perform multiple arithmetic operations on two numbers
def add_sub_mult_div(a, b):
""" This function returns the results of addition and subtraction of the two numbers """
i = a + b
j = a - b
k = a * b
l = a / b
return i, j, k, l
# Storing the result of the function in to a variable r
r = add_sub_mult_div(10, 5)
# Displaying the result of the function
print('The results are: ')
for x in r:
print(x, end=',')
# Result:
The results are:
15,5,50,2.0
# ------------------------------------------------------------------------------------------------------------------------ #
Defining a function inside another function:
We can define a function inside another function as shown in below example.
Example:
def fun1(str1):
def fun2():
return 'How are you? '
result = fun2()+str1
return result
# calling the fun1()
print(fun1('Mr. James Bond'))
# assigning a function to a variable
z = fun1('Mr. Goldfinger')
print(z)
# Results:
How are you? Mr. James Bond
How are you? Mr. Goldfinger
Pass by Object Reference :
In other programming languages like C and Java, we can pass a value to a function by using the concept of Call by Value or Call by Reference. But in Python, neither of these concepts is applicable.
In general, Call by Value represents that a copy of the variable value is passed to a function and any modifications to that value will reflect out side the function.
Similarly, the Call by Reference represents sending the reference or memory address of the variable to the function. The variable value is modified by function through memory address and hence the modified value of the variable value will reflect outside function also.
However, these concepts are not applicable in Python.
In Python, the values are passed to functions by means of object references, as everything is considered as an object.
All the numbers, strings, tuples, lists, dictionaries are considered as objects in Python.
For example, when we store a value in to a variable as:
x = 10
In other programming languages, first a variable x is created and memory is allocated to it and then a value 10 is stored into it.
In Python, in this case, an object(memory block) 10 is created in memory and then a name x is tagged to it. The objects are created based on the heap memory(RAM), which is available during the run time.
To know the memory location of the Object, we use the id() function. This id may change from a machine to machine:
x = 10
print('The memory location of x is: ', id(x))
# Result:
The memory location of x is: 1489707270672
When we pass values like numbers, strings, tuples or lists to a function, the references of the objects are passed to a function. Lets understand this concept with below program.
Example:
In the following program, we are creating a user defined function, modify(x) and assigning or modifying the the value of x as 15.
Next while calling the function, are passing the x value as 10.
We are displaying the id values of x inside the function and outside the function as well.
def modify(x):
"""reassign a value to the variable"""
x = 15
print(x, id(x))
# calling the function modify() and pass x
x = 10
modify(x)
print(x, id(x))
#Output:
15 2110697898672
10 2110697898512
From the output, we understand that, inside the function the object 15 is created in memory and it is referenced by the name x. This object is not available outside the function.
When we pass the object reference to the function, 10 as the object its reference name is x.
Still, inside the function it displays the 15, as the integer objects are immutable. Once it come outside the function it displays the another object value as 10.
Notes:
In Python, integers, floats, strings and tuples are immutable which means their original value in the memory cannot be modified. If we try to change their value, then a new object will be created in the memory with the modified value.
On the other hand, the lists and dictionaries are mutable, which means their value can be changed, the same object value will be modified and new object will not be created.
In the following program, when we pass a list of values(numbers) to a modify() function, and then when we append a element to the list inside the function, the same list will be modified and hence the modified list will be outside the function as well.
Example:
def modify(lst):
"""to add a element to a list"""
lst.append(8)
print(lst, id(lst))
# calling the function modify() and pass lst
lst = [1, 2, 3, 4]
modify(lst)
print(lst, id(lst))
#Result:
[1, 2, 3, 4, 8] 1606158375552
[1, 2, 3, 4, 8] 1606158375552
Conclusion:
In Python values are passed to a function by object references. If the object is immutable, the modified value is not available outside the function. If the object is mutable, the modified value is available outside the function as well.
#--------------------------------------------------------------Thanks--------------------------------------------------------------#
No comments:
Post a Comment
Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.