0% found this document useful (0 votes)
8 views5 pages

Python Notes 20C - Scope Types In, Function

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)
8 views5 pages

Python Notes 20C - Scope Types In, Function

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/ 5

PYTHON Scope of Variables

Scope of Variables -

1) Local scope ( as function scope)

2) Global scope (using global keyword)

3) Class scope (using self convention (variable) ) for only OOPs

o Scope of variable refers to the part of the program, where it is accessible, (i.e.), area
where you can refer (use) it.
o We can say that scope holds the current set of variables and their values.

Types of scopes in functions : 1) local scope, 2) global scope

Local Scope

 A variable declared inside the function's body or in the local scope is known as local
variable.
 A variable with local scope can be accessed only within the function block that it is
created in.

Example:

Note: Local variable of function block cannot access outside the function block.

By E.V.VIJAYARAJ M.Sc., M.C.A., M.Phil., B.Ed., D.C.S&Engg., Page 1


PYTHON Scope of Variables

Global Scope

 A variable, with global scope can be accessed (used) anywhere in the program.
 It can be created by defining a variable outside the scope of any function block.

Example1

Example2 Treat as different variables as local scope and global

Example3

By E.V.VIJAYARAJ M.Sc., M.C.A., M.Phil., B.Ed., D.C.S&Engg., Page 2


PYTHON Scope of Variables

Rule:

 Without using the global keyword we cannot modify the global variable inside the
function but we can only print (access) the global variable.

The global keyword

 The global keyword can only be used in function block.


 It is mainly used for access/modify (or) create global variable in function.

Example1:

By E.V.VIJAYARAJ M.Sc., M.C.A., M.Phil., B.Ed., D.C.S&Engg., Page 3


PYTHON Scope of Variables

Example2:

By E.V.VIJAYARAJ M.Sc., M.C.A., M.Phil., B.Ed., D.C.S&Engg., Page 4


PYTHON Scope of Variables

Example : Global variable and Local variable with same name

By E.V.VIJAYARAJ M.Sc., M.C.A., M.Phil., B.Ed., D.C.S&Engg., Page 5

You might also like