Borislav Hadzhiev
Last updated: Jun 26, 2022
Check out my new book
The recommended style for multiline if statements in Python is to use
parenthesis to break up the if
statement. The PEP8 style guide recommends the
use of parenthesis 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') # 👇️ using backslash for line continuation (discouraged by pep8) 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 parenthesis, 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')
You 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 from 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 hard to read.
# ⛔️ BAD (same level of indentation for conditions and `if` body) if 'hi' == 'hi' and \ len('hi') == 2 and \ 2 == 2: print('success')