Rishabh
Rishabh

Reputation: 41

In which cases can I use indentations in python?

I was reading Python Language reference.

On lexical analysis page

Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated.

Here, it says that adding indent on a line will just add the value associated with INDENT to the indent tracking stack.


So I tried to do python equivalent of the C++ snippet

int x = 23;
{
    int y = 13;
}
int z = 2*x;

with this python snippet

x = 23
    y = 13
z = 2*x

But making python run this code generated following error:

    y = 13
IndentationError: unexpected indent

So the above rule doesn't apply all the time, I wanted to know

Upvotes: 2

Views: 125

Answers (2)

beliz
beliz

Reputation: 402

I think the most important usage of indentations is in loops. Because python does not have an end for loops like in Matlab, the lines with the correct indentation are in the loop.

Upvotes: 0

T. Gwen
T. Gwen

Reputation: 104

"At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated."

So here it tells you all about when indent token are generated. Now you also need to know that only the key words class, def, if, for, while, etc. allows you to have an additionnal current indent token.

"when I can use the indentation, other than the general cases like function and class definitions". -> Never.

Note : breaking line doesn't count as indent token. So :

>>> a = [1, 2, \  # \ is breaking line.
        3]

is possible, it doesn't technically count as indentation because it's the same python line. Same for function arguments :

>>> a = np.array([0,1],
                 dtype=float)

Upvotes: 1

Related Questions