Local variable scope in Java vs Python

1.8k views Asked by At

When I try to access the local variable jimFound outside of the block it was declared in the first Java code piece I get a compilation error

Error:(10, 13) java: cannot find symbol, symbol: variable jimFound, location: class Scope

Which is what I expected.

public class Scope { 
    public void main(String args[]){
        String name = "Jim";
        if (name.equals("Jim")) {
            boolean jimFound = true;
        }
        if(jimFound) {
            System.out.println("I found Jim!");
        }
    }
}

When I try the same with Python my program manages to find Jim.

name = "Jim"
if name == "Jim":
    jim_found = True
if jim_found:
    print "I found Jim!"

The console result is "I found Jim!"

Why is this happening?

1

There are 1 answers

1
aadarshsg On BEST ANSWER

Python variables are scoped to the innermost function or module; control blocks like if and while blocks don't count.

What's the scope of a Python variable declared in an if statement?