2

I need help to explain the following behaviour, Why x is a global variable?

def y():

    print(x)

if __name__ == "__main__":

    x=5
    a = y()

output: 5

1 Answers1

2
if __name__ == "__main__":

doesn't define a new/local scope. It's designed to protect execution of the below block from happening when the module is imported by another module.

So defining x within this block makes it global, and it works because you're calling the function after having defined it.

note that importing this very module and calling y from there will raise an error because the definition of x won't be executed

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219