x=5
def printx()
print x
x=10
running this gives unboundlocal error
but when my function is just print x i get no error..
x=5
def printx()
print x
x=10
running this gives unboundlocal error
but when my function is just print x i get no error..
Simply assigning a value to x in the function is making it a local variable, therefore shadowing the global x = 5 specified on the previous line. And on the line you're trying to print x, the local version of x hasn't been initialized yet. It is curious how doing something on a later line is influencing lines that come before it, but that's just how it works.
You don't need any special declaration to read a global variable, therefore it works without the assignment inside the function. However, if you'd rather assign 10 to the global x instead of making a new, local x, you'll have to specify global x inside the function.