Introduction to Python's if
and elif Statements
Python is a versatile programming language known for its
simplicity and readability. One of the fundamental
constructs in Python, and indeed in most programming
languages, is the ability to make decisions based on
conditions. This is where the if and elif statements come
into play. These statements allow your program to execute
certain pieces of code only if specific conditions are met.
Let's dive into how these work in Python with some
examples.
Understanding if Statements
An if statement in Python is used to test a condition. If the
condition evaluates to True, the block of code inside the
if statement is executed. If the condition is False, the
block of code is skipped.
Syntax of if Statement:
if condition:
# code to execute if the condition is true
Example
Let's look at a simple example where we check if a
number is positive:
number = 10
if number > 0:
print("The number is positive.")
In this example, the condition number > 0 evaluates to
True because 10 is greater than 0. Therefore, the message
"The number is positive." is printed.
Introducing elif Statements
The elif (short for "else if") statement allows you to check
multiple conditions. If the if condition is False, Python
checks the elif condition. If the elif condition is True, the
corresponding block of code is executed. You can have
multiple elif statements to check various conditions.
Syntax of elif Statement
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition1 is false and condition2
is true
Example
Let's extend our previous example to also check if the
number is negative or zero:
number = -5
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
In this example:
The if condition number > 0 evaluates to False.
Python then checks the elif condition number < 0,
which evaluates to True.
Therefore, the message "The number is negative." is
printed.