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
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ya i understood that, but still For and if also considered as block right?
@Mathan yes, they are blocks, but not scopes. See also stackoverflow.com/q/291978/3001761.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.