1

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?

PetMarion
  • 147
  • 3
  • 14
  • 1
    In Java a variable is scoped inside its _block_ - simply said the closest pair of curly brackets (with some exceptions). So `jimFound` only exists _inside_ the `if` statement. – Boris the Spider Jun 09 '15 at 09:13

1 Answers1

4

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?

Community
  • 1
  • 1
aadarshsg
  • 2,069
  • 16
  • 25
  • So it's just a very different approach of scoping, but I find it very confusing. This way in Python it happens a lot to get a "UnboundLocalError: local variable 'some_variable' referenced before assignment" – PetMarion Jun 15 '15 at 11:28