Functions in Python
Functions
A function is a code block which is used to do the specific task whenever it is called. Suppose you need to do the same task many times in a program, what will you do? Well, you can make a code block which performs that partiular task and you name that block and whenever you need to perform that you can call that code block called as functions. Functions improve code reusability. Functions can be pre-defined or user defined. Pre-defined are those which are already coded in prpgramming language. You just have to use them. User-defined are those, which the programmers define to simplify the task they needed. There are many functions in Python which are pre-defned, print function that we use to print the statement is also pre-defined. To make a function is Python we use def keyword.
Syntax : def fun():
statements
Functions can also return some value as we will se in the coming exmaples. For returning the value we use return keyword. To call the function we just have to write the name of function and the parameters if needed. Parameters are the value that are needed to give the functions to perform the task.
Syntax : def fun(param1, param2):
statements
param1 and param2 are the parameters which are passed to the function. When we call the function we need to paas the value to these parameters. Let's see the example of function -
E.g. # function to add the numbers
def add(num1, num2):
reutrn num1 + num2
num3 = add(2, 3)
print(num3) # Output : 5
You can call the parameters as arguements also. You can pass as many arguements/paramters as you want. Parameters should be passed according to the way they are needed in the function. For example, you need two arguements, name and rollno then you pass the value of name for the name parameter and value of roll no to the rollno paramter.
E.g. def user(name, rollno):
print(name + ' ' + rollno)
user(12, 'John') # This is not correct. This will not give the error but this is not right way.
user('John', 12) # This is correct.
So, be careful while passing the arguements to the function.
Types of parameters/arguements :
Required arguements : These are the types of arguements that you need to pass to the function at the time of calling. If you do not pass them then there will be definitely error. For example in above add function we need to pass the two arguements otherwise there will be error. If you do not pass them then how will you perform the task? You need to pass the same numbers of arguements as needed. If there are two required then you need to pass two arguements compulsory otherwise there will be error.
Default arguements : These are the arguements that are optional to give to the function at the time of calling. Basically you already set the value to the parameters at the time of function creation. Now at the time of calling if you pass the value of arguements then that value will be set for that arguement otherwise default value will be used. Default parameters should be last in order to pass to the function, otherwise there will be conflict among the values. Suppose you already set the name a deafult value then you will set that parameters always last in order, both at the time of creation and function calling.
E.g. def user(id, name = "admin"):
print(name +"have id "+id)
user(10) # output : admin have id 10
user(10, "John") # output : John have id 10
Variable length parameters : Sometimes there are the cases where we do not know in advance that how many total parameters are needed. So we can use variable length parameters to pass the number of arguements we need in the function. Those arguements are written as individual value but treated as tuple internally. We use *args for these type of parameters. There can be any name inplace of args. We can iterate those parameters also as they are tuples.
E.g. def func(*nums):
res = sum(nums) * 100
return res
func(2, 5, 6) # output : 1300
func(4, 1) # output : 500
func(7, 1, 6, 3, 2, 9) # output : 2800
Keywords arguements : We can also call the function with keywords arguements. If we follow this approach then we can pass the parameters in random order because now there will be no conflict among values as they have their keyword now.
E.g. def func(name, age):
print("Age of "+ name + "is "+ age)
func(name = "Clay", age = 21) # Age of Clay is 21
func(age = 21, name = "Clay") # Age of Clay is 21
We can pass multiple keyword arguements also. It works in the same way as *args but the differene is that here arguements are dictionary. Here we use **kwargs.
E.g. def func(**names):
print(len(names))
func(a = 'Clay', b = 'Justin', c = 'Hannah') # output : 3
func(x = 'Tony', z = 'Chris') # output : 2
Lambda Functions :
In Python we can also define the function in a shorter way but without any name for the function and we can do this with lambda keyword. Lambda functions are generally inline.
Syntax : lambda arguements : statement
We assign the lambda function to some variable.
E.g. sq = lambda x : x**2
print(sq(5)) # output : 25
Lambda function can take any number of arguements but only one return statement.
E.g. mul = lambda x, y : x*y
print(mul(2, 5)) # output : 10
There can be multiple lambda together. Lets see how -
E.g. f = lambda a: lambda b: lambda c: a*b*c
print(f(5)(3)(2)) # output : 30
f = lambda c: lambda a, b: lambda d: (c*(a+b))%d
print(f(2)(4, 3)(11)) # output : 3
filter function : filter() function accepts the function and a list as an arguement. It helps to filter out the elements from the arguement list on the basis of provided function.
E.g. even = list(filter(lambda x: x%2 == 0, [2, 3, 4, 5, 6]))
print(even) # output : [2, 4, 6]
map function : map() function accepts the function and list as an arguements. It helps to modify the value of list items on the basis of given arguement function.
E.g. sq = list(map(lambda x: x**2, [1, 2, 3, 4]))
print(sq) # output : [1, 4, 9, 16]
Recursion :
This topic belongs to the data structure part and important one. Recursion means function calling the function again and again. In recursion there is a sort of loop in which a function calls another function.
E.g. # Program to print the factorial of any number.
def fact(n):
if n==1 or n==0:
return 1
else:
n = n*fact(n-1)
return n
print(fact(3)) # output : 6
Comments
Post a Comment