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

Python | Introduction

Python is developed by Guido van Rossum . Guido van Rossum started implementing python in 1989. Python is very simple programming language so if you are new to programming, you can learn python without facing any issue. Features of Python Free and Open Source -                                                                                      Python is a open source language. We can easily install python.It is freely available at python's official website . High level language -                                                                                     ...

Python | Data Structure Or Data Types (Sets)

Data Type Of Python In this section we will see new data type which is Sets. 3) Sets:- Set object is an unordered collection of distinct unhashable object. The common user include membership test removing duplicate from a sequence and computing mathematical operation such as intersection, union, differences etc.     Being an unordered collection set do not record element position or order of insertion. Accordingly set do not support indexing, slicing, stepping or other sequence like behavior.      We declare a set by using curly braces {}. Note:- Set can only store immutable data. Empty set:-  S = set() Set with multi element:- S = {10, 'Hi', (10, 20)} Membership:- print(10 in S) => True print(20 in S) => False Iteration:- for i in S:       print(i)  => 10       'Hi'       (10,20) Type casting:- S = "Programming" S2 = set(S) print(S2) => {'p', 'r', 'o', 'g', 'a', 'm', 'i', 'n'} In the ...

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 ...