0

In python, local variable can be accessed only inside a block. According to python block will start with :[colon] and all the statements inside the block will have same indentation. But in for loop and in if statement am using a local variable and its able to access outside the block. Can anyone explain how its possible. Code is as follows:

def a():
    for i in range(0,4):
        i=i+1
    print(i)
    if(True):
        ii=10
        print("Inside",ii)
    print("Outside",ii)
a()

Output:
4
Inside 10
Outside 10
Daniel Roseman
  • 541,889
  • 55
  • 754
  • 786
Mathan
  • 75
  • 10

1 Answers1

0

Your assertion that "local variable can be accessed only inside a block" is just not true in Python, as your code demonstrates.

The only things that introduce scope in Python are modules, classes, and functions.

Daniel Roseman
  • 541,889
  • 55
  • 754
  • 786