Skip to main content

Python | Function In Python

Function In Python

Function is a block of code which perform particular task. The function only runs when it is called. You can pass data in the function using parameters. 

Types Of Function:-
1) Built-in-function
2)User Defined Function
3) Recursive Function
4) Anonymus Function (lamda)

In this section we will see about user defined function. Remaining types of function we will see later one by one.

User Define Function
    Now we see how to define function in python program. To define function in python def is the keyword followed by function name and parenthesis (). You can add any input parameters in this parenthesis. 

Syntax
def myfunction():
        print("Hello world")

Here by using def keyword we define function myfunction() as a name with parenthesis. To defining function colon is important after the parenthesis. The code inside the function must be intended as shown in syntax.

Example of Function:-
def myfunction():
     print("Hello World")
myfunction()

Output:-
Hello World

Now we see another example using function:-
def add(a,b):
     C=a+b
     print("Adition is:",C)
add(3,5)

#Output
#Adition is: 8

In this example we create a function add with the parameters a and b. In the function body we write a code to perform addition and print the output. To call the function we write the function name with the values of a and b in the parenthesis outside the function body. And here we get the proper output of the program. 
 
You can write this code without using function.
a = 3
b = 5
C=a+b
print("Addition is",C)

Output:
Addition is: 8

 
Function Parameters:-

1) Positional Parameter:- These are mandatory and they don't have default value. They Raises error if we missed to pass.
For example:-    

ex1. 
def add (a,b):
        C=a+b
        print(C)
add(3,5)

Output:
8


ex2.
def add (a,b):
        C=a+b
        print(C)
add(3) 

Output:
TypeError
 

In the ex1. we call the function with proper values of a and b. And we get actual output. But in the ex2. we call the function with missing value of parameter b so it return TypeError. 
    In the Positional type parameter you must have to give the values of all parameter if you forgot to give value to one parameter the it will raise an error.

2) Keyword Parameter :- This are not mandatory and they have default value. They can be overwritten at the time of function calling.
For example:-
ex1.
def add (a,b=10):
        C = a+b
        print(C)
add(3) 

Output:
13

ex2.
def add (a,b=10):
        C=a+b
        print(C)
add(3,5)

Output:
8

In ex1. we give the default value to b parameter. And at the time of function calling we give only value of a parameter. So here value of a is 3 and value of b is 10 which is default value.

In ex2. we give the default value to b parameter. But at the time of function calling we give value of both a and b. So the value of b become changes. That means it is over written. So here the value of a is 3 and value of b is changes to 5. 

3) Arbitary Positional Parameter:-  It returns tuple of arbitary positional parameter. We use star(*) to unpack tuple.
For example:-
def foo(*args):
     c=0
     for i in args:
          c+=i
     return c
t = tuple(range(1,11))
print(foo(*t))

Output:
55

In this example we pass tuple as a parameter. That means we pass tuple t in this function. * is used to unpack the tuple so we get the addition of first 10 number. This program is for addition of first 10 numbers. By modify this program you can find addition of first n numbers.

4) Arbitary Keyword Parameter:- It is a dictionary of keyword parameter. We use double star (**) to unpack dictionary.
For example:-
def foo(**kwargs):
     for k,v in kwargs.items():
          print(f'key is: {k},value is: {v}')
d={'a':10,'b':20,'c':30}
foo(**d)

Output:
key is: a,value is: 10
key is: b,value is: 20
key is: c,value is: 30

In this Session we see how to define function in python and function parameters. By defining function you can do any program. We will see some programs using functions.

Examples:-
1) Write the python program to identify the given number is even or odd.
Ans:-

def is_even(n):
        if n%2 == 0:
            print(f'{n} is the even number')
        else:
            print(f'{n} is odd number')
is_even(8) #Calling Function

Output:
8 is the even number

2) Write a program to store square of n numbers in the list.
Ans:-

def square(n):
        L1 = []
        for i in range(n):
                L1.append(i*i)
        print(L1)
square(20) #Square of first twenty numbers.

Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]


Like that you can write programs using function. We will see more program later. In the next session we will see about recursive function. 

Comments

Popular posts from this blog

Basic Knowledge of Python part 2

Strings using python - Other than numbers python can also handle strings which can be expressed by several ways. In programming a string is a contiguous sequence of symbols or values such as a character string or digit string. Strings is declared in a '....' (single quotes) or "...." (double quotes).     By using  '\n'  you can insert the string to the new line by using  print()  command. For example:  We can concatenate string by using + operator. Concatenate means we can merge two or more separate strings by using + operator. For example: We see another example of multiple concatenate. Here 3*'py' means the string 'py' repeats 3 times and same for the 'thon' string. Now we another method to concatenate two or more strings. In this method you have write strings next to each other without any operator. For example: In the python string is stored in indexes. The index is start from 0 (zero). In python indexes also be calculated from reve...

Python | Data Structures or Data Types (List)

Data Type of Python In Python there are two types of data types which are Mutable and Immutable. Mutable data type contains List and Dictionary data types. And Immutable data type contains String,Tuple and Sets data types. Now we see what is Mutable and Immutable data type? The main object get changed permanently after applying methods of data type this data type is called as Mutable data type. And the main object will not be changed permanently after applying methods of data type this data type is called as Immutable data types. Now we see data types one by one! 1) List - List is an ordered collection of mutable datatype. Lists are hashable, iterable. List contain any kind of data. List are declared in square braces[]. Empty List-  L = [ ] List with multiple elements -  L1 = [10, 15.10, 'Python', [10,20] ] In the above list you can add any data type as shown above. In list L1 there is Integer, float,String,list data types. To add string data type you must have to declared in ...

Basic Knowledge of Python part 1

Basic Mathematics equations using Python- As we know python is a simple and easy to learn programming language. In this section we learn how to done mathematics equations using python. To perform this we use our basic operators +,-,/,* .  To perform python we have to open python interpreter. In this interpreter you can type simple equation like 5+5, 4/2 etc. For example: The integer number (e.g. 1,2,3....) have type int and the number with fractional part (e.g. 2.5,2.1,4.5...) have type float. Note:-  The division type always returns float. To get only an integer result of division you can use the // operator and to get remainder from division result you can use % operator. In python you can easily calculate power of the number by using ** operator. Like this you can easily calculate mathematics equation. Now we see how to find area of rectangle. Area = length*width is the formula to find area of rectangle. Here '=' sign is used to store value to the variable. You can als...