Function is defined as a self contained block of statements that performs a specific task. It provides a way to reuse the code again & again, in this way function allows a group of programmers or a team to use the same code. It improve the readability of the code.
Use def keyword to define the function.
Use lowercase letters and numbers while naming the function. If function name contains multi-words then separate those words with _ (underscore) character. Always start function name with smallcase letters.
Let us see in the following examples, how to define the functions in Python. I will start with a little/simple one and move towards advanced.
"""
created_at : 11 Feb 2017.
updated_at : 11 Feb 2017.
aim of script : To understand the concept of functions in Python.
coded by : Rishikesh Agrawani.
Python version : 2.7.12
"""
#Example 1
def sum(a,b): #definition of function named sum, which takes 2 parameters, adds those parameters and
return a+b #returns the result to its caller
print sum(10,5) #15 [calling sum() with 10 and 5 ]
print sum(6,8) #14 [calling sum() with 6 and 8]
print sum("Banga","lore") #Bangalore [calling sum() with 'Banga' and 'lore']
#Example 2
def print_from_last(nums): #A function that prints list elements from end 1-by-1
for num in reversed(nums): #Iterating through a 'listreverseiterator' object
print num
print_from_last([5,6,0,3,2,1])
#Example 3
def addition_of_all(nums): #A funtion that returns the sum of all numbers/items of list/tuple argument passed to it
s = 0 #variable s initialized with 0
for num in nums: #iterating through the list/tuple of items(numbers)
s += num #s = s+num
return s #returning the sum
print addition_of_all( [1,2,3,4,5] ) #15 [calling addition_of_all() with 1 list argumnet having 5 numbers]
print addition_of_all( (11,22,33) ) #66 [calling addition_of_all() with 1 tuple argument having 3 numbers]
#Interactive mode programming
>>> def square(n): #A function named square that takes 1 argument and retuns the square
... return n**2 #n**2 => n*n
...
>>> print square(10)
100
>>>
>>> print square(11)
121
>>>
>>> print square(5)
25
>>>
>>> def cube(n): #A function named cube that takes 1 argument and returns the cube
... return n**3 #n**3 => n*n*n
...
>>> print cube(5)
125
>>>
>>> print cube(6)
216
>>>
>>> print cube(7)
343
>>>
>>> print cube(8)
512
>>>
>>> print cube(3)
27
>>>