0% found this document useful (0 votes)
10 views

Functions

Uploaded by

Junaid Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Functions

Uploaded by

Junaid Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Made by Saurabh Arora

Function
A function is a set of statements .

A function can take inputs, do some specific


computation and can produce output.
def func_name():

Advantage-
Instead of writing the same code again and again for different
inputs, we can call the function.

Made by Saurabh Arora


Everything
Types of Functions with a () is a
function
1. Modules

import math

a=math.sqrt(9)

b=math.pow(4,2)

2. In built functions – len(), max(), min()

3. User Defined Functions

Made by Saurabh Arora


User Defined Function (Example-1)

Function Definition No input is given to


keyword function name
function and function
is also not returning
def say_hello(): any thing
print(“Hello”)
print(“How are you”)
print(“I am Inside Function”)

Function Call

say_hello()

function name
Made by Saurabh Arora
Example - 2
Function Definition
parameters 2 inputs are given to
function and function
is not returning any
def add(a,b): thing

c=a+b
print(c)

Function Call
add(5,8)

Arguments
Made by Saurabh Arora
Example - 3
parameters

2 inputs are given to


def multiply(a,b): function and function
is also returning a
c=a*b value
return c

x=multiply(5,8)
print(x)
Arguments

Made by Saurabh Arora


Parameters are the variables which are present
in the function definition.

Arguments are the values provided in


function call statement that are passed to the
function definition.

Made by Saurabh Arora


Scope of Variables

Scope of variable refers to the part of the


program, where it is visible, i.e., area where
you can use it.

We will study two types of scope of variables-


1. global scope
global scope exists
2. local scope outside any function.

local scope exists inside


any function

Made by Saurabh Arora


Global Scope

A variable, with global scope can be used anywhere in the


program. It can be created by defining a variable outside
the scope of any function.
A variable created in global scope (outside function) is
known as global variable

Example -
x=50
def test ( ):
print (“Inside test x is” , x)
print (“Value of x is” , x )
test()

Output -

Value of x is 50
Inside test x is 50
Made by Saurabh Arora
When global variable x is modified inside the function

Example -
x=10
def test(): global keyword should
global x be used , otherwise error
x=x+8
print ("Inside test x is" , x)
print ("Value of x is" , x ) We can only access the global
test() variable inside any function but we
print ("Value of x is" , x ) cannot modify it inside any
function.
Output –
For modifying a global variable you
should use global keyword.
Value of x is 10
Inside test x is 18
Value of x is 18
Made by Saurabh Arora
Local Scope

A variable with local scope can be accessed only


within the function that it is created in.

A variable created in local scope (inside function) is known


as local variable

A local variable only exists while the function is executing.

A local variable can not be


accessed outside any
function

Made by Saurabh Arora


Example
x=10 A local variable can not be
def test(): accessed outside any
y=20 function
print("x=",x)
print("y=",y)
test()
print("x=",x) Wrong because y is a
print("y=",y) local variable

Output –
x= 10
y= 20
x= 10
Traceback (most recent call last):
File "C:/Python34/zz.py", line 8, in <module>
print("y=",y)
NameError: name 'y' is not defined
Made by Saurabh Arora
Most Important - 1

When Global variable and Local Variable have


same name

def f():
Local Variable and
s = "I Love London!" Global Variable both
print(s) #local variable have same name

s = "I Love Paris!"


f()
print(s) Note- Two choices inside
function

Output – Python hides the global


variable and prints the local
I Love London! variable inside function.
I Love Paris!

Made by Saurabh Arora


Most Important - 2

When Global variable and Local Variable have same


name

def f():
global s
Global keyword tells
print(s) python to treat the
s = "Inside Function" variable as global. Here
print(s) s variable that is used
inside function is global
s = "Outside Function" variable.
f()
print(s)

Output –
Outside Function
Inside Function
Inside Function

Made by Saurabh Arora


Most Important - 3

When Global variable and Local Variable have same


name
def f():
print(s) #global variable
Local Variable and
s = "I Love London!" Global Variable both
print(s) #local variable have same name

s = "I Love Paris!"


f()
print(s)
Note- Python does not
Output – allow this ambiguity -
Traceback (most recent call last): local variable and
global variable inside
File "C:\Python34\sss.py", line 7, in <module>
same scope that’s why
f() error occurred.
File "C:\Python34\sss.py", line 2, in f
print(s)
UnboundLocalError: local variable 's' referenced before assignment

Made by Saurabh Arora


Positional Arguments in a Function
The positional arguments are arguments that are
written in proper position or sequence

 Value for each and every parameter should be sent from


function call

def simple_interest(p,r,t):
print("p=",p)
print("r=",r)
print("t=",t)
si=p*r*t/100
return si

x=simple_interest(1000,5,1) Wrong because value for t


x=simple_interest(1000,5) is not sent

Made by Saurabh Arora


Default Arguments in a Function
The default values are only written in function definition
 The default values are used only when no value of that variable is
received from the function call.

 The value for that variable which has no default argument , should
always be sent from function call to function definition like the value
for p is being sent through function call in below example

def simple_interest(p,r=8,t=2):
print("p=",p) Default
print("r=",r) Arguments are
print("t=",t) always
si=p*r*t/100 assigned from
return si right to left

x=simple_interest(1000,5,1)
x=simple_interest(1000,5)
x=simple_interest(1000) Wrong because p does not
x=simple_interest() have a default argument in
function definition
Made by Saurabh Arora
Keyword (Named) Arguments in a Function
The keyword arguments are arguments in which the
parameters names are given with their values in
function call statement

Adv.- Remembering order of arguments is not important in


function call statement

def simple_interest(p,r,t):
print("p=",p)
print("r=",r)
print("t=",t)
si=p*r*t/100
return si Correct, because
ordering does not
x=simple_interest(p=1000,r=5,t=1) matter here
x=simple_interest(t=1,r=5,p=1000)
Made by Saurabh Arora
Combining Default , Positional and Keyword
Arguments

Remember – Positional Arguments should always be on the left of


Keyword Arguments

def simple_interest(p,r,t=2):
print("p=",p)
print("r=",r) Correct, because p is positional
print("t=",t) argument, r is keyword argument,
si=p*r*t/100 t is default argument.
return si
Error because positional
x=simple_interest(10000,r=8) arguments is not on the left
of keyword argument.

x=simple_interest(r=8,10000)
Error because multiple values
for p are being sent to
x=simple_interest(10000,p=10000) function
Made by Saurabh Arora
random module

Functions inside random module --

1. randint(a,b) - It will return a value x such that a<=x<=b

>>>import random
It will return a
>>>random.randint(1,6) value x such that
5 1<=x<=6

Made by Saurabh Arora


Practice Questions

Ques. Predict the correct output(s)

import random
print(random.randint(0,5)+20,end=":")
print(random.randint(0,5)+20,end=":")
print(random.randint(0,5)+20,end=":")
print(random.randint(0,5)+20)

i) 20:21:22:23
ii) 19:25:25:22
iii) 22:23:26:24
iv) 23:23:23:23
Made by Saurabh Arora
Practice Questions

Ques. Study the following program and select the possible output(s) from the
options (i) to (iv) following it. Also, write the maximum and the minimum
values that can be assigned to the variable Temp during the overall execution
of program.

import random
Series=[0,2,4,6]
for Count in range(0,4):
Temp = random.randint( Series[Count], Count*3)
print(Temp,":",end="")

i) 0:0:4:6
ii) 0:2:5:7
iii) 0:3:7:8
iv) 0:4:6:9
Made by Saurabh Arora
Practice Questions

Ques. What possible outputs(s) are expected to be displayed on screen at the time
of execution of the program from the following code? Also specify the maximum
values that can be assigned to each of the variables FROM and TO.

import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO+1):
print (AR[K],end=“#”)

(i) 10#40#70# (ii) 30#40#50#


(iii) 50#60#70# (iv) 40#50#70#

Made by Saurabh Arora


random module

2. random() - It will return a value x of float type such


that 0<=x<1. (1 is not included)

>>>import random It will return a


value x such that
>>>random.random()
0<=x<1
0.9213043091472363

Made by Saurabh Arora


random module

Ques. Predict the correct output(s)

import random
print(int(random.random()*5+20),end=" ")
print(int(random.random()*5+20),end=" ")
print(int(random.random()*5+20),end=" ")
print(int(random.random()*5+20),end=" ")

i) 20 21 22 23
ii) 20 25 25 22
iii) 22 23 25 24
iv) 23 23 23 23
Made by Saurabh Arora
random module

3. uniform(a,b) - It will return a value x of float type


such that a<=x<b . (b is not included)

>>>import random It will return a


>>>random.uniform(5,10) value x such that
5<=x<10
5.512300164842275

Made by Saurabh Arora


random module

4. randrange(start,stop,step) - It will return a value x of


type int such as numbers from start to stop at intervals of step values
(stop value is not included)

>>>import random
>>>random.randrange(100,150,3)
100
>>>random.randrange(100,150,3)
103
>>>random.randrange(100,150,3)
130
>>>random.randrange(100,150,3)
148
Made by Saurabh Arora
math Module

Functions inside math module --

1. ceil(x) – next possible integer

2. floor (x) – previous possible integer

3. fabs(x) – gives absolute value of x

4. exp(x) – gives exponential of x means ex


5. log(x) – gives natural log of x means logex

6. log10(x) - gives log to base 10 of x means log10x

7. pow(x,y) – gives x to the power y means xy

8. sqrt(x) – gives square root of x


Made by Saurabh Arora
math Module

9. sin(x) - It gives sine of x where x is in radians

10 cos(x) – It gives cosine of x where x is in radians

11 tan(x) – It gives tangent of x where x is in radians

12. degrees(x) – It converts angle x from radians to degrees

13. radians(x) – It converts angle x from degrees to radians

Made by Saurabh Arora


Passing Immutable Type to functions

def increment(n):
n=n+1
print("n=",n)

a=3
increment(a)
print("a=",a)

Output: The variable a and n will both refer


to value 3 inside function but as soon
n= 4 as value of n is increased by 1 , n
starts referring to value 4 and a is
a= 3 still referring to value 3.

Made by Saurabh Arora


Passing Immutable Type to functions

Solution: Only for changing the values of immutable variables,


use return statement

def increment(n):
n=n+1
print("n=",n)
return n

a=3
a=increment(a)
print("a=",a)

Output:

n= 4
a= 4
Made by Saurabh Arora
Passing Mutable Type to functions

def increment(n):
n.append(4)

L=[1,2,3]
increment(L)
print("L=",L) The List variable L and the
variable n refer to the same list
and the changes done in n
Output: variable will also be seen in L
variable.
L= [1, 2, 3, 4]

Made by Saurabh Arora


return statement
A return statement is used to end the execution of the function
definition and returns the result to the calling function. The
statements written after the return statements are not executed
Here, return statement is not
def func(x): returning anything, only flow
of execution will go back to
return function call statement
print(x)
Not executed

a=func(5) # this program will do nothing


print(a) # Output will be None

A special value None is returned back from the function


here. It means no value or nothing. It is not same as 0
(zero) or an empty string . None is a keyword in python.
Made by Saurabh Arora
return statement returning more than one
value

def func(x):
return x,x+1,x+2,x+3

Z=func(1) Output will be


print(Z) returned in the form
of tuple.

Output:
(1, 2, 3, 4)

Made by Saurabh Arora


return statement returning more than one
value (another method)

def func(x):
return x,x+1,x+2,x+3

a,b,c,d=func(1) Still Tuple is being returned


print(a,b,c,d) from function but the values
are getting stored into
different variables because of
Output: Tuple Unpacking
1234

Made by Saurabh Arora

You might also like