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

Python | Data Structure or Data Types (String)

Data Type Of Python I n the last session we discus about what is the data type of python. And we see List data type. In this session we s ee the next data type String.     2) String- String is a ordered collection of immutable data type. String are iterable and hashable. Strings are always declared in single or double quotes.  Single line string:- S = "Python" Multi line string:- S = """ Line 1             Line 2             Line 3 """ Iterable:- S= "Program" for i in S:       print(i) Output:-  P  r  o  g  r  a  m Membership:-  print( 'p' in S) => True print( 'P' not in S) => False Methods of string:- capitalize() :-  It return the capitalize version of the string. More specifically it make the first character have uppercase and rest lowercase. For example:- S = "hello World" print(S.capitalize()) => "Hello world" count(substring, start,en...

Python | Data Structure Or Data Type (Tuple)

Data Type Of Python  In this session we will see last data type of python which is Tuple. 5) Tuple:- Tuple is a ordered collection of immutable datatype, tuples are quite similar to lists but difference is list are mutable where as tuple are immutable. Empty tuple:-  t = () or tuple() Tuple with single element:- t = (10,) Tuple with multiple element:- t1 = ( 10, 20, 30, 'Hello' ) Nested tuple:-  t1 = ( 10, 20, 30, 'Hello' ) p = t2, 30, 40, 50 print(p) => ((10, 20, 30, 'Hello'), 30, 40, 50) Methods of Tuple:-   count(value):- It return the count of value if the value is present in the tuple else it return 0. For example:- t = (10, 20, 30, 'Hello') t.count(10) => 1  t.count(50) => 0 index(value,start,end):- It return the index number if the value is present in the tuple, otherwise it raised value error. For example:- t = (10, 20, 30, 'Hello') t.index(10) => 0 It return the index number of value 10. Prev Topic   Next Topic