I'm new to python, and wondering why it can access the variable defined in main program from outside, but can't in a self-defined function.
def f():
print(l)
if __name__ == '__main__':
l = [1,2,3]
f() # output: [1,2,3]
but encounter error when do it in a function
def f1():
l1 = [1,2,3]
f2()
def f2():
print(l1) # error: global name 'l1' is not defined
if __name__ == '__main__':
f1()
The first example really confused me, AFAIK, it's an error in C/C++ or some other languages, because we can't reference a undefined variable. So why it's legal here and why the second example is not legal?