PDA

View Full Version : Indentation levels and scope (Python)




unbelly
Mar 27, 2012, 08:44 AM
Hey there. I'm going through a tutorial on python and programming for beginners, have been following up until now but am having some trouble understanding what exactly they mean by 'indentation level' here:


The Accessible Variable Pattern
A variable is accessible with respect to a particular scope if it is in scope. A variable is in scope if it is local or was defined in a scope that encloses the particular scope. Some scope A encloses some other scope B if, by moving (perhaps repeatedly) leftward from scope B, scope A can be reached. Here is example:

Z = 5

def f(x):
return x + Z

print(f(3))

The variable Z is local with respect to the global scope and is non-local with respect to f. However, we can move leftward from the scope of f one indentation level and reach the global scope where Z is defined. Therefore, the global scope encloses the scope of f and thus Z is accessible from f. Indeed, the global scope encloses all other scopes and this is why the built-in functions are accessible at any indentation level.

I just want to double check that I properly understand what they mean by 'indentation level'.
Are they talking about the line spaces between the lines of code (as in a space between two lines) or about how far inside a line the code is indented? Or both?



naples98
Mar 27, 2012, 07:54 PM
Z = 5

def f(x):
return x + Z

print(f(3))


I would check the tutorial you are doing because what you posted above should probably look like the code below.


Z = 5

def f(x):
return x + Z

print(f(3))


When writing functions in languages like Java or C++, the statements belonging to a function are grouped by { }.


void myFunction()
{
//do something
}


However, Python uses indention instead of the {} to group statements belonging to a function so the function would be

void myFunction():
//do something