Conditional Statements in Python
Conditional Statements in Python
In the real world, we commonly must evaluate information around us and then
— FREE Email Series — choose one course of action or another based on what we observe:
🐍 Python Tricks 💌 If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather
isn’t nice, then I won’t mow the lawn.)
In a Python program, the if statement is how you perform this sort of decision-
making. It allows for conditional execution of a statement or group of statements
based on the value of an expression.
by John Sturtz Sep 05, 2018 12 Comments time. Lastly, you’ll tie it all together and learn how to write complex decision-making
basics python code.
if <expr>:
<statement>
From the previous tutorials in this series, you now have quite a bit of Python code If <expr> is true (evaluates to a value that is “truthy”), then <statement> is executed.
under your belt. Everything you have seen so far has consisted of sequential If <expr> is false, then <statement> is skipped over and not executed.
execution, in which statements are always performed one after the next, in exactly
the order specified. Note that the colon (:) following <expr> is required. Some programming languages
require <expr> to be enclosed in parentheses, but Python does not.
But the world is often more complicated than that. Frequently, a program needs to
skip over some statements, execute a series of statements repetitively, or choose Here are several examples of this type of if statement:
between alternate sets of statements to execute.
Help
That is where control structures come in. A control structure directs the order of
execution of the statements in a program (referred to as the program’s control flow).
Python >>>
If the weather is nice, then I will:
>>> x = 0
>>> y = 5 Mow the lawn
Weed the garden
>>> if x < y: # Truthy
... print('yes') Take the dog for a walk
...
yes (If the weather isn’t nice, then I won’t do any of these things.)
>>> if y < x: # Falsy
... print('yes')
...
In all the examples shown above, each if <expr>: has been followed by only a single
<statement>. There needs to be some way to say “If <expr> is true, do all of the
>>> if x: # Falsy following things.”
... print('yes')
... The usual approach taken by most programming languages is to define a syntactic
>>> if y: # Truthy
device that groups multiple statements into one compound statement or block. A
... print('yes')
... block is regarded syntactically as a single entity. When it is the target of an if
yes statement, and <expr> is true, then all the statements in the block are executed. If
<expr> is false, then none of them are.
>>> if x or y: # Truthy
... print('yes') Virtually all programming languages provide the capability to define blocks, but
...
they don’t all provide it in the same way. Let’s see how Python does it.
yes
>>> if x and y: # Falsy
... print('yes')
... Python: It’s All About the Indentation
Python follows a convention known as the off-side rule, a term coined by British
>>> if 'aul' in 'grault': # Truthy
... print('yes') computer scientist Peter J. Landin. (The term is taken from the offside law in
... association football.) Languages that adhere to the off-side rule define blocks by
yes indentation. Python is one of a relatively small set of off-side rule languages.
>>> if 'quux' in ['foo', 'bar', 'baz']: # Falsy
... print('yes') Recall from the previous tutorial on Python program structure that indentation has
...
special significance in a Python program. Now you know why: indentation is used to
define compound statements or blocks. In a Python program, contiguous
Note: If you are trying these examples interactively in a REPL session, you’ll statements that are indented to the same level are considered to be part of the same
find that, when you hit Enter ↩ after typing in the print('yes') statement, block.
Because this is a multiline statement, you need to hit Enter ↩ a second time Python
to tell the interpreter that you’re finished with it. This extra newline is not
1 if <expr>:
necessary in code executed from a script file.
2 <statement>
3 <statement>
4 ...
5 <statement>
6 <following_statement>
Remove ads
Here, all the statements at the matching indentation level (lines 2 to 5) are
considered part of the same block. The entire block is executed if <expr> is true, or
Grouping Statements: Indentation and skipped over if <expr> is false. Either way, execution proceeds with
So far, so good.
But let’s say you want to evaluate a condition and then do more than one thing if it is
true:
Notice that there is no token that denotes the end of the block. Rather, the end of
the block is indicated by a line that is indented less than the lines of the block itself.
Note: In the Python documentation, a group of statements defined by Note: In case you have been wondering, the off-side rule is the reason for the
indentation is often referred to as a suite. This tutorial series uses the terms necessity of the extra newline when entering multiline statements in a REPL
block and suite interchangeably. session. The interpreter otherwise has no way to know that the last statement
of the block has been entered.
Consider this script file foo.py:
Python
Windows Command Prompt The tactic used by most programming languages is to designate special tokens that
mark the start and end of a block. For example, in Perl blocks are defined with pairs
C:\Users\john\Documents>python foo.py
After conditional
of curly braces ({}) like this:
Blocks can be nested to arbitrary depth. Each indent defines a new block, and each
C/C++, Java, and a whole host of other languages use curly braces in this way.
outdent ends the preceding block. The resulting structure is straightforward,
consistent, and intuitive.
Python
if 10 > 20: # x Other languages, such as Algol and Pascal, use keywords begin and end to enclose
print('Inner condition 1') # x
blocks.
print('Between inner conditions') # x
1 >>> x = 120
Many programmers don’t like to be forced to do things a certain way. They tend
2 >>>
to have strong opinions about what looks good and what doesn’t, and they 3 >>> if x < 50:
don’t like to be shoehorned into a specific choice. 4 ... print('(first suite)')
5 ... print('x is small')
Some editors insert a mix of space and tab characters to the left of indented
6 ... else:
lines, which makes it difficult for the Python interpreter to determine 7 ... print('(second suite)')
indentation levels. On the other hand, it is frequently possible to configure 8 ... print('x is large')
editors not to do this. It generally isn’t considered desirable to have a mix of 9 ...
10 (second suite)
tabs and spaces in source code anyhow, no matter the language.
11 x is large
Like it or not, if you’re programming in Python, you’re stuck with the off-side rule. All
control structures in Python use it, as you will see in several future tutorials. There is also syntax for branching execution based on several alternatives. For this,
use one or more elif (short for else if) clauses. Python evaluates each <expr> in turn
For what it’s worth, many programmers who have been used to languages with and executes the suite corresponding to the first that is true. If none of the
more traditional means of block definition have initially recoiled at Python’s way but expressions are true, and an else clause is specified, then its suite is executed:
have gotten comfortable with it and have even grown to prefer it.
Python
if <expr>: An arbitrary number of elif clauses can be specified. The else clause is optional. If it
<statement(s)>
is present, there can be only one, and it must be specified last:
else:
<statement(s)>
Python >>>
Here’s one possible alternative to the example above using the dict.get()
Here, on the other hand, x is greater than 50, so the first suite is passed over, and the method:
second suite executed:
Python >>> Python
Recall from the tutorial on Python dictionaries that the dict.get() method 1. If <expr> is true, execute <statement_1>.
searches a dictionary for the specified key and returns the associated value if it
Then, execute <statement_2> ... <statement_n> unconditionally, irrespective
is found, or the given default value if it isn’t.
of whether <expr> is true or not.
An if statement with elif clauses uses short-circuit evaluation, analogous to what 2. If <expr> is true, execute all of <statement_1> ... <statement_n>. Otherwise,
you saw with the and and or operators. Once one of the expressions is found to be don’t execute any of them.
true and its block is executed, none of the remaining expressions are tested. This is
demonstrated below: Python takes the latter interpretation. The semicolon separating the <statements>
has higher precedence than the colon following <expr>—in computer lingo, the
Python >>> semicolon is said to bind more tightly than the colon. Thus, the <statements> are
>>> var # Not defined treated as a suite, and either all of them are executed, or none of them are:
Traceback (most recent call last):
Python >>>
File "<pyshell#58>", line 1, in <module>
var
>>> if 'f' in 'foo': print('1'); print('2'); print('3')
NameError: name 'var' is not defined
...
1
>>> if 'a' in 'bar':
2
... print('foo')
3
... elif 1/0:
>>> if 'z' in 'foo': print('1'); print('2'); print('3')
... print("This won't happen")
...
... elif var:
... print("This won't either")
... Multiple statements may be specified on the same line as an elif or else clause as
foo
well:
Python >>>
The second expression contains a division by zero, and the third references an
undefined variable var. Either would raise an error, but neither is evaluated because >>> x = 2
the first condition specified is true. >>> if x == 1: print('foo'); print('bar'); print('baz')
... elif x == 2: print('qux'); print('quux')
... else: print('corge'); print('grault')
...
qux
quux
Remove ads
>>> x = 3
>>> if x == 1: print('foo'); print('bar'); print('baz')
Python
if <expr>: While all of this works, and the interpreter allows it, it is generally discouraged on
<statement> the grounds that it leads to poor readability, particularly for complex if statements.
PEP 8 specifically recommends against it.
But it is permissible to write an entire if statement on one line. The following is
As usual, it is somewhat a matter of taste. Most people would find the following
functionally equivalent to the example above:
more visually appealing and easier to understand at first glance than the example
above:
Python >>> Python >>>
Python name a few. In fact, the ?: operator is commonly called the ternary operator in
those languages, which is probably the reason Python’s conditional expression
debugging = True # Set to True to turn debugging on.
is sometimes referred to as the Python ternary operator.
.
. You can see in PEP 308 that the <conditional_expr> ? <expr1> : <expr2>
. syntax was considered for Python but ultimately rejected in favor of the syntax
shown above.
if debugging: print('About to call function foo()')
foo()
A common use of the conditional expression is to select variable assignment. For
example, suppose you want to find the larger of two numbers. Of course, there is a
built-in function, max(), that does just this (and more) that you could use. But
Conditional Expressions (Python’s Ternary suppose you want to write your own code from scratch.
Python But a conditional expression is shorter and arguably more readable as well:
>>> x = y = 40
Here, the empty curly braces define an empty block. Perl or C will evaluate the
If you are using a conditional expression as part of a larger expression, it probably is expression x, and then even if it is true, quietly do nothing.
a good idea to use grouping parentheses for clarification even if they are not
needed. Because Python uses indentation instead of delimiters, it is not possible to specify
an empty block. If you introduce an if statement with if <expr>:, something has to
Conditional expressions also use short-circuit evaluation like compound logical come after it, either on the same line or indented on the following line.
expressions. Portions of a conditional expression are not evaluated if they don’t
need to be. Consider this script foo.py:
if True:
If <conditional_expr> is true, <expr1> is returned and <expr2> is not evaluated.
If <conditional_expr> is false, <expr2> is returned and <expr1> is not evaluated. print('foo')
As before, you can verify this by using terms that would raise an error:
If you try to run foo.py, you’ll get this:
Python >>>
Windows Command Prompt
>>> 'foo' if True else 1/0
Table of Contents
C:\Users\john\Documents\Python\doc>python foo.py
'foo' Introduction to the if Statement
File "foo.py", line 3
>>> 1/0 if False else 'bar' Grouping Statements:
print('foo')
'bar' Indentation and Blocks
^
IndentationError: expected an indented block The else and elif Clauses
In both cases, the 1/0 terms are not evaluated, so no exception is raised. One-Line if Statements
Conditional Expressions
The Python pass statement solves this problem. It doesn’t change program behavior
Conditional expressions can also be chained together, as a sort of alternative (Python’s Ternary Operator)
at all. It is used as a placeholder to keep the interpreter happy in any situation where
if/elif/else structure, as shown here: The Python pass Statement
a statement is syntactically required, but you don’t really want to do anything:
Python >>> → Conclusion
Python
>>> s = ('foo' if (x == 1) else
if True:
... 'bar' if (x == 2) else Mark as Completed
... 'baz' if (x == 3) else pass
... )
>>> s Tweet Share Email
Now foo.py runs without error:
'baz'
All of these concepts are crucial to developing more complex Python code.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who
The next two tutorials will present two new control structures: the while statement worked on this tutorial are:
and the for statement. These structures facilitate iteration, execution of a
statement or block of statements repeatedly.
Aldren Brad Joanna
Take the Quiz: Test your knowledge with our interactive “Python
Conditional Statements” quiz. Upon completion you will receive a score so you
can track your learning progress over time:
Mark as Completed
Watch Now This tutorial has a related video course created by the Real
Python team. Watch it together with the written tutorial to deepen your
understanding: Conditional Statements in Python (if/elif/else)
Commenting Tips: The most useful comments are those written with the
goal of learning from or helping out other students. Get tips for asking
good questions and get answers to common questions in our support
portal.
Keep Learning
Remove ads