Java and Python printing variables differently

java, python, scope

Solution

Python has no variable declarations. Instead, it defines a rule that any name you assign to in a function is a local variable of that function. That means that the line

c = c + 1

in `foo` makes `c` a local variable, so

print c

tries to print an unassigned local variable and raises an exception.

Java has variable declarations. Your Java code declares `c` outside `main` and doesn't redeclare it inside, so Java knows that `c` is a static variable, and the program works. A better translation of the Python code to Java might be

public class Test1 {

    static int a = 1;
    static int b = 2;
    static int c = 3;

    public static void foo() {
        int c; // Now c is local, like in the Python
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        c = c + 1;
    }   

    public static void main(String[] args) {
        foo();
    }   
}

Problem

I am learning about variable scoping and was looking through some threads when I saw the following Python code: ``` a = 1 b = 2 c = 3 def foo(): print a print b print c c = c + 1 def main(): foo() main() ``` which prints out `1` `2` and `UnBoundLocalError: local variable 'c' referenced before assignment`. When I translated this to Java ``` public class Test1 { static int a = 1; static int b = 2; static int c = 3; public static void foo() { System.out.println(a); System.out.println(b); System.out.println(c); c = c + 1; } public static void main(String[] args) { foo(); } } ``` It prints out `1` `2` `3`. I am pretty sure I translated it correctly(highly embarrassing if it isn't). My question is why does Python give an error whereas Java does not? Is it something to do with different scoping or the way that they are interpreted and compiled?

Original source

Related problems