2

I am coming from C, C++, and Java background. So I am curious to know why the following Python code works:

def f1():
    print(xy)


if __name__ == "__main__":
    print("Hello")
    xy = 34
    f1()

It prints:

Hello
34

How can I access xy in function f1? xy is not defined inside f1 also, xy is defined in a conditional block of if __name__ == "__main__"?

ncica
  • 7,015
  • 1
  • 15
  • 37
user3243499
  • 2,953
  • 6
  • 33
  • 75
  • Does this answer your question? [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – gstukelj Nov 21 '19 at 11:24
  • Python does not have enclosing scopes that you are used to in `C++`. At the line `xy = 34`, the variable `xy` is entered into the local module scope. – quamrana Nov 21 '19 at 11:24

2 Answers2

5

Global Variables

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

ncica
  • 7,015
  • 1
  • 15
  • 37
  • That is fine, I can understand it as a global variable. What I didn't understand is, that `xy` variable has been defined in an `if` condition. How can an `if` condition variable be accessed outside its block? – user3243499 Nov 21 '19 at 15:26
  • 1
    If statement is not a function, variables declared in a function are local variables, and everything declared outside of the function are globals – ncica Nov 21 '19 at 19:10
0

While in many or most other programming languages variables are treated as global if not otherwise declared, Python deals with variables the other way around. They are local, if not otherwise declared.

def f():
   print(x)
x = "Something"
f()

This prints "Something"

Khalil
  • 410
  • 5
  • 13