if Tests
The Python
if
statement selects actions to perform.
It’s the primary selection tool in Python and represents much
of the logic a Python program possesses. It’s also our first
compound statement; like all compound Python
statements, the if
may contain other statements,
including other ifs
. In fact, Python lets you
combine statements in a program both
sequentially (so that they execute one after
another), and arbitrarily nested (so that they
execute only under certain conditions).
General Format
The Python
if
statement is typical of most procedural
languages. It takes the form of an if
test,
followed by one or more optional
elif
tests (meaning “else if”),
and ends with an optional
else
block. Each test and the
else
have an associated block of nested statements
indented under a header line. When the statement runs, Python
executes the block of code associated with the first test that
evaluates to true, or the else
block if all tests
prove false. The general form of an if
looks like
this:
if <test1
>: # if test <statements1
> # associated block elif <test2
>: # optional elif's <statements2
> else: # optional else <statements3
>
Examples
Here are two simple examples of the
if
statement. All
parts are optional except the initial if
test and
its associated statements. Here’s the first:
>>>if 1:
...print 'true'
... true >>>if not 1:
...print 'true'
...else:
...print 'false'
... false
Now, here’s an example of the most complex kind of
if
statement—with all its optional parts present. ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.