Python function

The Python function is a block of instructions. It can be defined as a sub-program. Every function will have its own specific task and purpose. If you want to divide your program systematically or categorize each code performing a specific task differently, then you can definitely use a function.

Some uses of a function are given below:
 
a)To split complex procedure/programs into smaller parts.
 
b)To improve maintainability.
 
c)To improve readability.
 
d)To reduce code duplication: If you have a specific code that should be used again and again, instead of writing it repeatedly you can make a function consisting of that code. In this way, if you need the code you can call the function instead of writing the whole code.


How to define Python function

Defining a function is simple :

i)First of all write the keyword ‘def‘.

ii)Then write the name of the function. The name can be anything, but it is better that the name symbolizes the code the function will hold. Say, if you are going to write a code to generate prime numbers then you can give the function name as ‘primeNumberGenerator’.

iii)Thirdly, after the function name, there should be a pair of braces ‘()‘. Inside this braces, you can write some names to accept some input parameter (more about this is discussed below).

iv)The braces are followed by a colon ‘:‘ .The colon signifies the end of the function definition name.

v)Next to the colon, we have the body of the function. The body is where you placed your codes.

vi)The function may return some values or not. If you want the function to return anything then use the keyword ‘return‘ and write whatever value you want to return after the return keyword.

Following the above rule we can define a function as.

>>> def func():
	print("Inside func()")

To call a function simply write the function name with the braces.

>>> func() #calling the func() function
Inside func()

The ‘Inside func()’ is printed out since we have called the func() function.

More examples are given below.



Passing values to the function

In order to pass a value or values to the function we must write some names inside the braces. The names inside the braces will let the function know that it is accepting some values from the outside.

The function add(a, b) below will add two numbers which are passed from the outside.

>>> def add(a , b):
     print('a=',a,'\nb=',b) #prints 'a' and 'b' values
     print('a+b=',a+b) #prints the sum

	
>>> add(90 , 89)  #Calling 'add' function
a= 90 
b= 89
a+b= 179

If the names ‘a’ and ‘b’ are not mentioned inside the braces then we cannot pass any values to the function.

Also, if you want to pass three values to the function then you have to mention three different names inside the braces.

>>> def func():
     print("Inside func()")

>>> func( 90 ) #error! cannot pass value to func()
...
TypeError: func() takes 0 positional arguments but 1 was given
>>> #---------------------------
>>> def func12( a , new): #func12() accpet two values
     print('a=',a,'\nnew=',new)

>>> func12( 90 , 876 , 'Tuesday') #error cannot pass three values
...	
SyntaxError: duplicate argument 'a' in function definition

To ‘func’ function we tried passing 90 but we got an error message because ‘func’ cannot accept any value.

The ‘func12’ function can accept only two values, but we passed three values, so we got an error message.

The function ‘SameName’ has two same names inside the braces, so we got an erorr. Note the name inside the braces is known as parameter.


Returning value by the function

If the function must return a value then the keyword ‘return’ is used and then whatever value is to be returned is placed next to the return keyword.

 
>>> def Add(a , b):
	return a+b

>>> sum=Add(34 , 9.99 )
>>> sum
43.99

The ‘Add’ function returns the sum of ‘a+b’ . The returned value is assigned to ‘sum’ which is then printed out. Instead of assigning the returned value to any other object, we can also print it out directly as shown below.

 
>>> from decimal import Decimal as D #this is neccesary
>>> print('55.788+090.354=',Add( D(55.788) , D(090.354) ) )
55.788+090.354= 146.1419999999999959072738420

The ‘Decimal’ type is used to get better precision digits.

Link :Python fraction and decimal

The function can return any data type: list, tuple, dictionary, set, string, etc. you name it.

>>> def func():
	ls=[23 ,67 , 90]
	return ls

>>> print( func() )
[23, 67, 90]

The function above returns a list.

Here is another function that points out which number is a prime number and which are not. Pass two values so that the function can determine the prime nubmer within the range of the two values.

>>> def PrimeNumberGenerator( a , b ):
	if a==0: #check if the first value is 0
		print(a,'is not prime')
		a=a+1
	if a==1: #check if the fist or second value is 1
		print(a,'is not prime')
		a=a+1
	for item in range(a , b+1):
		for n in range(2 , item):
			if (n!=item) & (item%n==0):
				print(item,'is not a prime number')
				break
		else:
			print(item,'is a prime number!!')

>>> PrimeNumberGenerator(0, 20)
0 is not prime
1 is not prime
2 is a prime number!!
3 is a prime number!!
4 is not a prime number
5 is a prime number!!
6 is not a prime number
7 is a prime number!!
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number!!
12 is not a prime number
13 is a prime number!!
14 is not a prime number
15 is not a prime number
16 is not a prime number
17 is a prime number!!
18 is not a prime number
19 is a prime number!!
20 is not a prime number

I am sure the function is easy to understand. If you don’t know what the range() function does visit the link given below. Also, a special else clause is used in the function.

Link :Python range() loop
Link :Python else clause on loop


Using functions as data type elements

In using the data types such as list, set, dictionary, etc. we can also use functions as its elements besides the data type objects or values.

If the object element is a function then we can no doubt call the function. Accessing the function element is the same as calling the function. Consider the code below.

>>> def f2():
...  return "f2() called"
...
>>> def f3():
...  return "f3() called"
...
>>> def f4():
...  return "f4() called "
...
>>> l=[f2() , 67.89 , f3() , f4()]
>>> l[0] #Calls f2()
'f2() called'
>>> l[2] #Calls f3()
'f3() called' 
>>> l[3] #Calls f4()
'f4() called ' 

The ‘l’ object has the f2(), f3() and f4() as its elements, so accessing a particular element calls the corresponding function.

We can also provide just the function name without the ‘()‘(bracket) as the element. Here to call the function, we must put extra bracket after the ‘[]’. The bracket is required only if the element is a function name.

>>> def f2():
...  return "f2() called"
...
>>> def f3():
...  return "f3() called"
...
>>> def f4():
...  return "f4() called "
...
>>> >>> lm=[f2 , 78, f4]
>>> lm[0]() #Calls f2()
'f2() called'
>>> lm[2]() #Calls f4()
'f4() called '

We must prefer the above method of utilising just the function name without the bracket as the element of an object, the reason is explained below.

If we provide the bracket with the function name as the element and if the function accept arguments, then it becomes quite hard for us to pass varied argument values. Consider the code below.

>>> def func( x ,y):
...  return x*y
...
>>> ll=[func(23 ,78), "New text"]
>>> ll[0] #Calling func(23 , 78) 
1794
>>> ll[0]
1794

Every time ll[0] is accessed, the func() is called with the argument as 23 and 78. There is no way to change the value of the arguments. However, if just the function name is utilized without the bracket, then passing different values become possible.

>
>>> def func( x ,y):
...  return x*y
...
>>> ls=[func , 34 , 'Functions as element']
>>> ls[0](12 , 90) #Calling func(12 ,90)
1080
>>> ls[0](100 ,67.78) #Calling func(100 , 67.78)
6778.0

As you can see, we can easily change the values passed to the function if the bracket is not part of the element. Well if you ever decide to make a function as the element of an object just free the bracket.

If you have any doubt or questions comment below.