In this chapter, we will discuss how to control the flow of our Python programs using conditional statements: if
, else
, and elif
.
The if
Statement
The if
statement is the most basic type of conditional statement in Python. It checks a condition and executes a block of code only if the condition is true.
x = 5 if x > 0: print("x is positive")
In this example, x > 0
is the condition. Since x
is 5
, and 5
is indeed greater than 0
, the print statement is executed.
Note the use of indentation to define the block of code to be executed if the condition is true. Python uses indentation (typically four spaces or one tab) to define blocks of code.
The else
Statement
The else
statement follows an if
statement and defines a block of code to be executed if the condition in the if
statement is false.
x = -5 if x > 0: print("x is positive") else: print("x is not positive")
In this case, x
is -5
, so x > 0
is False
. The if
block is skipped and the else
block is executed instead.
The elif
Statement
elif
is a contraction of “else if”. It allows us to check multiple conditions and execute a specific block of code as soon as one of the conditions is true.
x = 0 if x > 0: print("x is positive") elif x < 0: print("x is negative") else: print("x is zero")
In this example, x
is 0
, so x > 0
is False
and x < 0
is also False
. Both the if
and elif
blocks are skipped, and the else
block is executed.
Remember, the elif
and else
statements are optional. An if
statement can exist on its own or be followed by any number of elif
statements. The else
statement, if used, must come last.
With if
, else
, and elif
, you can make your Python programs make decisions and behave differently based on various conditions. This is a foundational concept in any programming language and critical in mastering Python.