Scope

I am taking an amazing Python course in Greek. In a Python quiz the following question appeared:

What will the following code print?
def f2():
  print(x)
  
def f1():
  x = 1 
  f2()

x=0
f1()

What are the options here?

Undeclared
My C-based mind is yelling UNDECLAAAAAARED! The C code below:

#include <stdio.h>
void f2()
{
printf(x);
}

void f1()
{
  int x = 1;
  f2();
}
void main(){
  int x = 0;
  f1();
}

gives:

error: 'x' undeclared

The number 1
The outer scope of the f2 call has x = 1 so the program will print 1. This is not the case, besides it does not make sense for every function to have access to the whole namespace of the caller.

What really happened is the third option:

The number 0
The Python program gives 0. That was not anticipated. I think the best explanation is the global/local dipole. Since x is not local inside f2 then Python is looking for a global variable with that name, finds it and prints it. So, if x was not global then f2 would have given an “undeclared error”. The following code:

def f2():
  print(x)
  
def f1():
  x = 1 
  f2()

def main():
  x=0
  f1()

main()

gives:

NameError: name 'x' is not defined
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s