Styling multiline if statements in Python

avatar

Borislav Hadzhiev

Last updated: Jun 26, 2022

banner

Check out my new book

Styling multiline if statements in Python #

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.

main.py
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.

The guide also recommends putting line breaks after the boolean operators 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.

main.py
# ✅ 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.

main.py
# ⛔️ 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.

main.py
# ✅ GOOD if ( 'hi' == 'hi' and len('hi') == 2 and 2 == 2 ): print('success')
When using this approach, you don't have to use extra indentation for the conditions because the closing parenthesis separates the conditions from the body of the 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.

main.py
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.

main.py
# ⛔️ BAD (same level of indentation for conditions and `if` body) if 'hi' == 'hi' and \ len('hi') == 2 and \ 2 == 2: print('success')
Use the search field on my Home Page to filter through my more than 3,000 articles.