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 | Recursive Function

Python - Recursive Function Recursive function means the function call themselves within the function body until a certain condition is matched then this function is recursive function. For example:-  def fact(n):      if n==0 or n==1:           return 1      else:           return n*fact(n-1) print(fact(8)) Output:- 40320 This is the example of recursive function. In this program we create a function named as fact and we call this function within the same function. How this program works? We give the value of n is 8 so n=8. In the first if condition, 8 is not equal to 0 and 1 so it goes to the else part in the else part the sentence is return n*fact(n-1) that means 8*fact(7) now here value of n become 7 to find fact(7) again same procedure repeat up to fact(1).   Because fact(1)=1   we give this condition. Then  fact(2) => 2*fact(1) =>  2*1 =>  2   ...

Python | Control Flow Tools

Control Flow Tools In this session we will see about control flow tools of python. 1) if Statement:- In the programming language if statement is important statement. Now we see how to write if statement in the python program. For Example:- >>> x = int(input("Please Enter an integer")) Please Enter an integer 50 >>> if x<0:      x=0      print("Negative change to zero") elif x==0: print("Zero") elif x==1: print("One") else: print("More") More >>>  Here is the program of if statement. You can add one or more elif part in the program. else part is the optional.      In the program we take the value of x is 50. In the if statement we write x<0 condition which is false because 50 is not less than 0 so it will go to the next part of the code which is first elif part, here we give condition x==0 this condition is also false so it will go to the second elif part which is x==1 this condition is also f...