Conditional Statements

# Conditional Statements

A conditional statement is a multi-line statement that allows Python to choose among different alternatives based on the truth value of an expression. A conditional statement always begins with an if header, which is a single line followed by an indented body. The body is only executed if the expression directly following if (called the if expression) evaluates to a True value. If the if expression evaluates to a False value, then the body of the if is skipped.

password = 'unicorn'


Password is correct


This code prints the text Password is correct if the string password has the value of unicorn. But if the string is not unicorn then nothing is printed to the screen. We can change this behavior by using an elif clause. elif is shorthand in Python for "else if".

password = 'bulldog'

print('Bulldogs go home!')

Bulldogs go home!


You can see that this if statement first checks to see if password has the value unicorn. In this case, it does not, so it checks the first elif clause. Since password has the value bulldog, this elif clause resolves True, it executes the code indented underneath it, so the phrase Bulldogs go home! is printed to the screen. Notice that even though the second elif clause is also true, bulldogs != unicorns, it does not execute this code. Only the first elif clause that evaluates True is executed.

You may have noticed in this example that the second elif clause acts as a catch all, since if neither of the first two statements run, then this last statement must be true. We could alternatively use an else statement to accomplish the same result:

password = 'frogs'

print('Bulldogs go home!')
else:

Incorrect password


## The General Form

A conditional statement can also have multiple clauses with multiple bodies, and only one of those bodies can ever be executed. The general format of a multi-clause conditional statement appears below.

if <if expression>:
<if body>
elif <elif expression 0>:
<elif body 0>
elif <elif expression 1>:
<elif body 1>
...
else:
<else body>

There is always exactly one if clause, but there can be any number of elif clauses. Python will evaluate the if and elif expressions in the headers in order until one is found that is a True value, then execute the corresponding body. The else clause is optional. When an else header is provided, its else body is executed only if none of the header expressions of the previous clauses are True. The else clause must always come at the end (or not at all).