- Python if statements (if, elif, else)
- if statements in Python: if , elif , else
- if
- if . else .
- if . elif .
- if . elif . else .
- Condition expressions in if statements
- Expressions that return bool (comparison operators, in operator, etc.)
- Non- bool cases
- Multiple conditions in if statements: and , or
- Negation in if statements: not
- How to write a conditional expression in multiple lines
- Related Categories
- Related Articles
- Python if and multiple lines
- # Styling multiline if statements in Python
- # Using extra indentation to differentiate between conditions
- # Moving all conditions in the if statement on separate lines
- # Using backslashes for line continuation
- # Additional Resources
Python if statements (if, elif, else)
This article explains conditional branching in Python using if statements ( if . elif . else . ).
Python also provides a ternary operator for writing single-line conditional branching. See the following article for more information:
if statements in Python: if , elif , else
The basic structure of the if statement is as follows. Blocks are expressed using indentation (usually four spaces).
if expression 1: Executed when expression 1 is True elif expression 2: Executed when expression 1 is False, and expression 2 is True elif expression 3: Executed when expressions 1 and 2 are False, and expression 3 is True . else: Executed when all expressions are False
Below are some examples. The def statement to define functions and f-strings to embed variables into strings are used.
if
When using only if , the specified process is executed if the condition evaluates to True , and nothing happens if it evaluates to False .
def if_only(n): if n > 0: print(f'n> is positive') if_only(100) # 100 is positive if_only(-100)
There is no need to enclose the condition expression in parentheses () . However, doing so won’t cause an error. Also, in the example, the process inside the block is only one line, but you can write a multi-line process as well.
if . else .
The else clause allows you to add a process for when the condition expression evaluates to False .
def if_else(n): if n > 0: print(f'n> is positive') else: print(f'n> is negative or zero') if_else(100) # 100 is positive if_else(-100) # -100 is negative or zero
if . elif .
With the elif clause, you can add processes for different conditions. elif is equivalent to else if or elseif in other programming languages and can be used multiple times.
Conditions are checked in order from the top, and the block associated with the first condition determined to be True is executed. If all conditions are False , nothing is done.
def if_elif(n): if n > 0: print(f'n> is positive') elif n == 0: print(f'n> is zero') elif n == -1: print(f'n> is minus one') if_elif(100) # 100 is positive if_elif(0) # 0 is zero if_elif(-1) # -1 is minus one if_elif(-100)
As mentioned below, you can also use and and or to specify multiple conditions in a single expression.
if . elif . else .
The elif and else clauses can be used together in the same conditional branching structure. Note that else must be the last.
The process in the else clause is executed when all preceding conditions evaluate as False .
def if_elif_else(n): if n > 0: print(f'n> is positive') elif n == 0: print(f'n> is zero') else: print(f'n> is negative') if_elif_else(100) # 100 is positive if_elif_else(0) # 0 is zero if_elif_else(-100) # -100 is negative
Condition expressions in if statements
Expressions that return bool (comparison operators, in operator, etc.)
As shown in the examples above, you can specify expressions that return bool ( True , False ) for the condition expressions in if statements, such as comparison operators.
Python has the following comparison operators:
See the following article for the difference between == and is .
In Python, you can chain multiple comparison operators, such as a < x < b .
You may also use in and not in to make a condition whether a list or string contains a specific element or substring.
def if_in(s): if 'a' in s: print(f'"a" is in "s>"') else: print(f'"a" is NOT in "s>"') if_in('apple') # "a" is in "apple" if_in('cherry') # "a" is NOT in "cherry"
You can also specify methods or functions that return bool as the condition in the if statement. For example, the startswith() method checks if a string starts with a specific substring.
def if_startswith(s): if s.startswith('a'): print(f'"s>" starts with "a"') else: print(f'"s>" does NOT starts with "a"') if_startswith("apple") # "apple" starts with "a" if_startswith("banana") # "banana" does NOT starts with "a"
Non- bool cases
In an if statement, you can use non-bool values, such as numbers or lists, and expressions that return those values as conditions.
if 100: print('True') # True if [0, 1, 2]: print('True') # True
In Python, the following objects are considered False :
- constants defined to be false: None and False .
- zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1)
- empty sequences and collections: » , () , [] , <> , set() , range(0) Built-in Types — Truth Value Testing — Python 3.11.2 documentation
Numeric values representing zero and empty strings and lists are considered False , while all other values are considered True .
This can be used to write simple conditions, such as checking if a list is empty, without retrieving the number of elements.
def if_is_empty(l): if l: print(f'l> is NOT empty') else: print(f'l> is empty') if_is_empty([0, 1, 2]) # [0, 1, 2] is NOT empty if_is_empty([]) # [] is empty
Note that non-empty strings are considered True , so the string ‘False’ is also considered True . To convert specific strings like ‘True’ or ‘False’ to 1 or 0 , use the strtobool() function from the distutils.util module. See the following article for more information:
Multiple conditions in if statements: and , or
To specify AND or OR of multiple conditions in an if statement, use and and or .
def if_and(n): if n > 0 and n % 2 == 0: print(f'n> is positive-even') else: print(f'n> is NOT positive-even') if_and(10) # 10 is positive-even if_and(5) # 5 is NOT positive-even if_and(-10) # -10 is NOT positive-even
You can also use and or or multiple times in a single condition expression.
def if_and_or(n): if n > 0 and n % 2 == 0 or n == 0: print(f'n> is positive-even or zero') else: print(f'n> is NOT positive-even or zero') if_and_or(10) # 10 is positive-even or zero if_and_or(5) # 5 is NOT positive-even or zero if_and_or(0) # 0 is positive-even or zero
The order of precedence for Boolean operators is not > and > or (with not being the highest). For more details, see the following article:
Negation in if statements: not
To specify NOT in the condition of an if statement, use not .
def if_not(s): if not s.startswith('a'): print(f'"s>" does NOT starts with "a"') else: print(f'"s>" starts with "a"') if_not("apple") # "apple" starts with "a" if_not("banana") # "banana" does NOT starts with "a"
However, for operators such as == or > , it is recommended to use their opposite counterparts, like != or
How to write a conditional expression in multiple lines
In cases where multiple conditional expressions are connected using and or or , and the line becomes too long, you may want to break the conditional expression into multiple lines.
You can break the line in the middle of the conditional expression by using backslash \ or by enclosing the entire expression in parentheses () .
The following three functions are equivalent, with the only difference being the writing style.
def if_no_newline(): if too_long_name_function_1() and too_long_name_function_2() and too_long_name_function_3(): print('True') else: print('False')
def if_backslash(): if too_long_name_function_1() \ and too_long_name_function_2() \ and too_long_name_function_3(): print('True') else: print('False')
def if_parentheses(): if ( too_long_name_function_1() and too_long_name_function_2() and too_long_name_function_3() ): print('True') else: print('False')
You can break the line multiple times using backslash \ or parentheses () , without indentation restrictions. This technique can be used in any Python code, not just in if statements.
Related Categories
Related Articles
- NumPy: Cast ndarray to a specific dtype with astype()
- Get calendar as text, HTML, list in Python
- nan (not a number) in Python
- Update tuples in Python (Add, change, remove items in tuples)
- Generate QR code image with Python, Pillow, qrcode
- String comparison in Python (exact/partial match, etc.)
- Measure elapsed time and time differences in Python
- Generate square or circular thumbnail images with Python, Pillow
- NumPy: Replace NaN (np.nan) in ndarray
- Shuffle a list, string, tuple in Python (random.shuffle, sample)
- Change dictionary key in Python
- Trigonometric functions in Python (sin, cos, tan, arcsin, arccos, arctan)
- Convert pandas.DataFrame, Series and list to each other
- Check pandas version: pd.show_versions
- Convert between Unix time (Epoch time) and datetime in Python
Python if and multiple lines
Last updated: Feb 19, 2023
Reading time · 2 min
# Styling multiline if statements in Python
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.
Copied!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.
# Using extra indentation to differentiate between conditions
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.
Copied!# ✅ 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.
Copied!# ⛔️ BAD (same level of indentation for conditions and body of if statement) if ('hi' == 'hi' and len('hi') == 2 and 2 == 2): print('success')
# Moving all conditions in the if statement on separate lines
You can also move all of the conditions in the if statement on separate lines.
Copied!# ✅ 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.
# Using backslashes for line continuation
Even though the PEP8 style guide discourages using backslashes for line continuation, it still is a perfectly valid syntax.
Copied!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.
Copied!# ⛔️ BAD (same level of indentation for conditions and `if` body) if 'hi' == 'hi' and \ len('hi') == 2 and \ 2 == 2: print('success')
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.