Functions - Ipynb - Colaboratory

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

18/11/2023, 19:18 Functions.

ipynb - Colaboratory

Function
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result. The main advantage of functions
is Code Reusability

Two basic types of function in Python :

1. Built-in Function : abs(), ascii(), bool() etc.


2. User defined function

def function_name(): Statement block return [expression ]

Note: Before calling a function you must define it .

Defining a function

In Python a function is defined using the def keyword.

The return statement is used to exit a function and go back to the place from where it was called.
This statement can contain expression which gets evaluated and the value is returned.

If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

def add_num(x,y):
sum = x+y
return sum

Calling a function

To call a function, use the function name followed by parenthesis:

print("The sum of x and y is:", add_num(5,10))

Parameters & Arguments


Parameters are specified during the definition of function while Arguments are passed during the
function call.

Parameters are inputs to the function. If a function contains parameters, then at the time of
calling,compulsory we should provide values, otherwise we will get error.

Types of parameters in Python:


https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 1/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory

1. Positional/Required Parameters: the number of arguments must be same and the order of
arguments is important.

2. Keyword (i.e.,Parameter name) Parameters: order of the arguments is not important but the
number of arguments must be same.

3. Default Parameters: You can define default parameters for the arguments. If you are not
passing any argument, then values by default will be considered. After default arguments you
should not take normal arguments.

4. Variable length Parameters: Sometimes we can pass variable number of arguments to our
function. We can declare a variable length argument with '*' symbol as follows:

def f1(*n):

We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

A parameter with single asterik contains non-keyworded variable-length arguments and a


double asterisk is placed before a parameter in function which can hold keyworded variable-
length arguments.

def add(a,b): #function definition


#here a and b are parameters

return a+b

print(add(12,13)) #12 and 13 are arguments

def calc(a,b): # Positional Arguments


sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div #Python function can return any number of values
t = calc(100,50)
for x in t:
print(x)

https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 2/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory

def calc(a,b): # keyword Arguments


sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
t = calc(b = 50, a = 100) # keyword Arguments #(100, b =50) is also valid
for x in t:
print(x)

def calc(a,b): # keyword arguments Arguments


sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
t = calc(b = 50, 100)
# It is invalid, because positional argument should follow keyword arguments.
# first keyword argument then possitional argument is not allowed.
for x in t:
print(x)

def wish(msg,name ='ABC'):


print(msg,name)
wish('Hello')

def wish(name ='ABC',msg):


# After default argument, we should not take non-default argument
print('Hello',name,msg)

def sum(a,b):
print(a+b) # This sum() function we can't use for the new requirement.
sum(10,20,30)

def sum(*n): # Here, 'n' is a variable length argument.


result = 0
for x in n:
result = result + x
print(result)
sum(10,20,30,40)

Now, Suppose if we want to pass any number of keyword arguments to a function. We can declare
key word variable length arguments also. For this we have to use **. We can call this function by
passing any number of keyword arguments. Internally these keyword arguments will be stored
inside a dictionary.

https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 3/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory

def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
display(rno=100,name="abc",marks=70,subject="Python")

Variable Scope and Lifetime


In python you cannot just access any variable from any part of your program.

Some of the variable not even exist for the entire duration of a program.

So for this purpose we must understand the two things regarding this:

Scope of the variable : part of the program in which a variable is accessible is called its scope.

Lifetime of the variable : Duration for which the variable exists is called its lifetime.

Global Variable:

Global variables are those variables which are defined in the main body of the program or outside of
the function. These variables can be accessed in all functions of that module.

Local Variable:

A variable which is defined within a function is called as local to that function only. A local variable
can be accessed from the point of its definition until the end of the function in which it is defined.

a = 10 # Global Variable
def f1():
a = 20 # Local variable to the function 'f1'
print(a) # 20
def f2():
print(a) # 10
f1()
f2()

def f1():
xy = 10 # local variable of 'f1()'
print(xy)
def f3():
print(xy) # local variable of 'f1()' can not accessed by function 'f3()'
f1()
f3()

global keyword: We can use global keyword for the following 2 purposes:

https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 4/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory

1. To declare global variables explicitly inside function.


2. To make global variable available to the function so that we can perform required
modifications.

a=10
def f1():
global a
# To bring global variable to the function for required modification
a=7
# we are changing the value of the local variable
print(a)
def f2():
print(a)
f1()
f2()

Lambda Function: Sometimes we can declare a function without any name,such type of nameless
functions are called anonymous functions or lambda functions. The main purpose of anonymous
function is just for instant use(i.e., for one time usage). The lambda function can return only one
value and doesn't have any explicit return statement. It cannot access a global variable. We can use
lambda functions very commonly with filter(),map() and reduce() functions,because these functions
expect function as argument. We can define by using lambda keyword:

lambda argument_list : expression

s=lambda a,b:a+b
print("The Sum of 10,20 is:",s(10,20))
print("The Sum of 100,200 is:",s(100,200))

s=lambda a,b:a if a>b else b


print("The Biggest of 10,20 is:",s(10,20))
print("The Biggest of 200,100 is:",s(200,100))

filter() function: We can use filter() function to filter values from the given sequence based on some
condition. For example, we have 20 numbers and if we want to retrieve only even numbers from
them.

Syntax:

filter(function,sequence)

Where, function argument is responsible to perform conditional check. sequence can be list or tuple
or string.

https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 5/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory

#without lambda
def isEven(x):
if x%2==0:
return True
else:
return False
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1)

[0, 10, 20, 30]

#with lambda
l=[0,5,10,15,20,25,30]
l1=list(filter(lambda x:x%2==0,l))
print(l1)
l2=list(filter(lambda x:x%2!=0,l))
print(l2)

[0, 10, 20, 30]


[5, 15, 25]

map() function:

For every element present in the given sequence,apply some functionality and generate new
element with the required modification. For this requirement we should go for map() function.

Syntax:

map(function,sequence)

The function can be applied on each element of sequence and generates new sequence

#without lambda
l=[1,2,3,4,5]
def doubleIt(x):
return 2*x
l1=list(map(doubleIt,l))
print(l1)

[2, 4, 6, 8, 10]

#With Lambda
l=[1,2,3,4,5]
l1=list(map(lambda x:x*x,l))
print(l1)

[1, 4, 9, 16, 25]

https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 6/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory

reduce() function:

reduce() function reduces sequence of elements into a single element by applying the specified
function.

Syntax:

reduce(function,sequence)

Note: reduce() function present in functools module and hence we should write import statement.

from functools import *


l=[10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result) # 150

150

https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 7/7

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy