The Python function is a block of instructions. It can also be defined as a sub-program. Every function will have its own specific tasks and purpose. So if you want to divide your program systematically or categorize each code performing a specific task differently then you can definitely use the 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, then instead of writing it repeatedly you can make a function 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 to symbolize the code that you are going to write. 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 aftet 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 name.
>>> 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) #returns 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() Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> func( 90 )#error 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 Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> func12( 90 , 876 , 'Tuesday') #error cannot pass thre values TypeError: func12() takes 2 positional arguments but 3 were given >>> #Function with duplicate names >>> def SameName(a , a): #Error print('a=',a) SyntaxError: duplicate argument 'a' in function definition
To ‘func’ function we tried passing 90 but we got an error message becasue ‘func’ cannot accpet any value.
The ‘func12’ function can accpet only two values but we tried passing 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.
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 will point 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 theo 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.
If you have any doubt or questions comment below.