It depends. As you already successfully tested, indentation may either have a significance or not in Python.
Indentation of blocks of code
The general rule is that all statements that belong to a block of code must be indented by the same amount of whitespace. The lowest level must not be indented.
def print_some_stuff(n_times, extra_line):
print('This is one level of indentation')
for i in range(n_times):
print(i + 1)
print('This is another one')
if extra_line:
print('This is one as well')
print('This is the lowest level (zero indentation)')
print_some_stuff(5, True)
The actual amount of whitespace is not fixed here, i.e. whether you indent all statements of a block of code by, say, 1, 4 or 20 spaces does not make a difference in terms of validity. The same is true for different amounts of whitespace for two different blocks of code. One block could theoretically be indented by 1 space and the next by 3, as long as indentation within each block is consistent.
def print_some_stuff(n_times, extra_line):
print('This is one level of indentation')
for i in range(n_times):
print(i + 1)
print('This is another one')
if extra_line:
print('This is one as well')
print('This is the lowest level (zero indentation)')
print_some_stuff(5, True)
Note that a block of code may also be (and often is) separated into multiple parts by another block of code: In the previous example for i in range(n_times)
and if extra_line
are on the same level and need to be indented identically.
However, varying indentation like in the last example is obviously not ideal and clear recommendations regarding style exist and should be followed (see the very end of this answer below).
If the indentation within a block of code is not consistent, Python will either raise an IndentationError
or a TabError
. This can even happen if the indentation visually seems to be identical but is in fact different, e.g. when mixing spaces and tab characters (in fact, that is a very common source of these errors, as SO posts like this one show).
Indentation within a statement
What you described in your question is not the indentation of different statements within a block of code, but rather indentation within a single statement. Statements can implicitly be continued across multiple lines if they are wrapped in parentheses or explicitly if each line (except the last of course) is ended by a single backslash (\
). Here, it does not matter how much whitespace precedes the continuing line. This is what you observed.
The following, while ugly and difficult to read, is completely valid:
def print_some_stuff(n_times,
extra_line):
print('This is one level of indentation')
for i \
in range(n_times):
print(i
+ 1)
print('This is another one')
if \
extra_line:
print('This is one as well')
print('This is the lowest level (zero indentation)')
print_some_stuff(5,
True)
Again, while valid, this is not recommended (see further below for what is).
Multi-line string literals
String literals can also be written across multiple lines. If multiple string literals are written sequentially, they are concatenated into one string, so the following examples all result in the string onetwothree
:
s1 = 'one' 'two' 'three'
s2 = 'one'\
'two' \
'three'
s3 = ('one'
'two'
'three')
s4 = ('one'
'two' \
'three')
This is basically the same as in the previous section, and the indentation of the individual lines does not matter.
However, there are also multi-line string literals which can be written using triple quotes. These behave differently, as they define a single string literal instead of concatenating several ones:
s5 = '''One
two
three'''
s6 = """one
two
three"""
The previous two string literals contain line breaks, i.e. are one\ntwo\nthree
. The line breaks can be suppressed by ending a line with a backslash:
s7 = '''one\
two\
three'''
As I said, since these define a single string literal, any "indentation" would actually be part of the string:
s8 = '''one
two
three'''
s9 = '''one\
two\
three'''
The first of these two is one\n two\n three
and the latter would be one two three
. So there is obviously a difference here based on how you "indent" the subsequent lines (which is why I personally do not like the triple quote approach except for comments or string literals on the lowest level).
Style (PEP-8)
While, as described above, different amounts of whitespace may be valid in different situations, the PEP8 - Style Guide for Python Code and specifically its section on indentation clearly defines how much whitespace to use in which situation.
I strongly encourage you to read the whole thing, but in short:
- Use 4 spaces per indentation level
- Spaces are the preferred indentation method
- Implicit continuation (within parentheses) is generally preferred over explicit (using backslashes)
- Continuation lines should be either vertically aligned with the opening delimiter or formatted using a hanging indent with an extra level of indentation
- Aligned with the opening delimiter
print_some_stuff(5,
True)
- When using hanging indents, place the first argument on a new line
def print_some_stuff(
n_times,
extra_line):
print('This is one level of indentation')
print_some_stuff(
5,
True)
There is more in PEP-8, including for instance details on where to put binary operators when breaking lines, etc., so go on and check it out.
This stuff is really well documented, so I'd go there instead of asking ChatGPT if I were you.