Nearby lessons

98 of 108

Python - Scope

Detailed Tutorial Notes

Note: Function vs Module vs Library:

  • A group of lines with some name is called a function
  • A group of functions saved to a file , is called Module
  • A group of Modules is nothing but Library Types of Variables Python supports 2 types of variables.
  • Global Variables
  • Local Variables
  • Global Variables The variables which are declared outside of function are called global variables. These variables can be accessed in all functions of that module. Eg:
1) a=10 # global variable
2) def f1():
3) print(a)

4)

5) def f2():
6) print(a)

7)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
10
10

Function 1

Function 2

Function 3

Module 1

Function 1

Function 2

Function 3

Module 2

Library

  • ----------------
  • ----------------
  • ----------------
  • ----------------
  • ----------------
  • ----------------
  • ----------------
  • ----------------
  • ----------------
  • Function
  • Local Variables: The variables which are declared inside a function are called local variables. Local variables are available only for the function in which we declared it.i.e from outside of function we cannot access. Eg:
1) def f1():
2) a=10
3) print(a) # valid

4)

5) def f2():
6) print(a) #invalid

7)

8) f1()
9) f2()

10)

11) NameError: name 'a' is not defined

global keyword:

We can use global keyword for the following 2 purposes:

  • To declare global variable inside function
  • To make global variable available to the function so that we can perform required modifications Eg 1:
1) a=10
2) def f1():
3) a=777
4) print(a)

5)

6) def f2():
7) print(a)

8)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
777
10

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Global Keyword