简体   繁体   中英

Why can I access variables that are conditionally defined outside of function in Python?

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__" ?

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM