0

Is there any importance for indentation when breaking a line (using backslash or parentheses) in python? How about the style recommendation, which one is recommended? I tried to ask bing chat/chatGPT for it, it thinks that the indentation is a must after breaking a line.

For example this code block:

def print_empty_square(size, c):
    for row in range(size):
        for col in range(size):
            if (row == 0 or row == size -1 
or col == 0 or col == size -1):
                   print(c,end = "")
            else:
                print(' ',end = "")
        print()
def print_empty_square(size, c):
    for row in range(size):
        for col in range(size):
            if (row == 0 or row == size -1 
             or col == 0 or col == size -1):
                   print(c,end = "")
            else:
                print(' ',end = "")
        print()

I tried both codes, they both run successfully. I asked bing chat and chatgpt for it and this is their answer:

Yes, indentation is very important in Python. Python uses indentation to indicate a block of code. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python treats the statements with the same indentation level (statements with an equal number of whitespaces before them) as a single code block¹³.

In your case, both codes run successfully because Python ignores blank lines and spaces at the beginning of a line when running code².

Source: Conversation with Bing, 02/04/2023(1) Python Indentation - W3Schools. https://www.w3schools.com/python/gloss_python_indentation.asp Accessed 02/04/2023. (2) Indentation in Python - GeeksforGeeks. https://www.geeksforgeeks.org/indentation-in-python/ Accessed 02/04/2023. (3) Indentation in Python | Python Indentation - Scaler Topics. https://www.scaler.com/topics/python/indentation-in-python/ Accessed 02/04/2023. (4) Why is indentation important in Python - tutorialspoint.com. https://www.tutorialspoint.com/Why-is-indentation-important-in-Python Accessed 02/04/2023.

buddemat
  • 4,552
  • 14
  • 29
  • 49
Eyal Cohen
  • 121
  • 6
  • 5
    ChatGPT, w3schools, geeksforgeeks ... It's like the who's who of terrible sources. – Kelly Bundy Apr 02 '23 at 20:49
  • 1
    @KellyBundy can't believe I'm defending geeksforgeeks, but the linked page doesn't actually say the attributed words "Python ignores blank lines and spaces at the beginning of a line when running code", or anything like them. This seems to be another case of an LLM fabricating sources for its hallucinations. – slothrop Apr 02 '23 at 21:59
  • Does this answer your question? https://peps.python.org/pep-0008/#indentation – mkrieger1 Apr 02 '23 at 23:32
  • Does this answer your question? https://docs.python.org/3/reference/lexical_analysis.html#implicit-line-joining – mkrieger1 Apr 02 '23 at 23:33

1 Answers1

3

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.

buddemat
  • 4,552
  • 14
  • 29
  • 49