Last updated: Apr 9, 2024
Reading timeยท2 min
The recommended style for multiline if statements in Python is to use
parentheses to break up the if
statement.
The PEP8 style guide recommends the use of parentheses over backslashes and
putting line breaks after the boolean and
and or
operators.
if ('hi' == 'hi' and len('hi') == 2 and 2 == 2): # ๐๏ธ Last lines with extra indentation print('success') # ๐๏ธ All conditions on separate lines if ( 'hi' == 'hi' and len('hi') == 2 and 2 == 2 ): print('success')
The preferred way to wrap long lines according to the official PEP8 style guide is to use Python's implied line continuation inside parentheses, brackets and braces.
The guide doesn't recommend using backslashes for line continuation.
and
and or
.The first example in the code sample uses extra indentation to differentiate
between the conditions in the if
statement and the code in the if
block.
# โ GOOD if ('hi' == 'hi' and len('hi') == 2 and 2 == 2): # ๐๏ธ Last lines with extra indentation print('success')
This makes our code more readable than using the same level of indentation for
the conditions and the if
block.
# โ๏ธ BAD (same level of indentation for conditions and body of if statement) if ('hi' == 'hi' and len('hi') == 2 and 2 == 2): print('success')
if
statement on separate linesYou can also move all of the conditions in the if
statement on separate lines.
# โ GOOD if ( 'hi' == 'hi' and len('hi') == 2 and 2 == 2 ): print('success')
if
statement.For longer if
statements, I find this a little easier to read than the
previous example.
Even though the PEP8 style guide discourages using backslashes for line continuation, it still is a perfectly valid syntax.
if 'hi' == 'hi' and \ len('hi') == 2 and \ 2 == 2: print('success')
When using this approach, make sure to add extra indentation for the last line(s) of conditions.
If you use the same level of indentation for the conditions and the body of the
if
statement, the code becomes difficult to read.
# โ๏ธ BAD (same level of indentation for conditions and `if` body) if 'hi' == 'hi' and \ len('hi') == 2 and \ 2 == 2: print('success')
You can learn more about the related topics by checking out the following tutorials: