Syntax error What are the rules for local and global variables in Python?

What are the rules for local and global variables in Python?



Scope of Variables in Python are of two types: local and global. Scope is defined as the accessibility of a variable in a region. Let us first understand both local and global scope before moving towards the rules.

Local Scope

Example

This defines the local scope of a variable i.e. it can be accessed only in the function where it is defined. No access for a variable with local scope outside the function. Let's see an example ?

# Variable with local scope can only be access inside the function def example(): i = 5 print(i) # An error is thrown if the variabke with local scope # is accessed outside the function # print(i) # Calling the example() function example()

Output

5

Global Scope

Example

If a variable is accessible from anywhere i.e. inside and even outside the function, it is called a Global Scope. Let's see an example ?

# Variable i = 10 # Function def example(): print(i) print(i) # The same variable accessible outside the function # Calling the example() function example() # The same variable accessible outside print(i)

Output

10
10
10

Rules for local and global variable

Following are the rules ?

  • Variables that are only referenced inside a function are implicitly global.

  • If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.

  • Variable with a local scope can be accessed only in the function where it is defined.

  • Variable with Global Scope can be accessed inside and outside the function.

Updated on: 2022-09-16T12:46:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements