Conditional Statements (if, elif, else)

Conditional Statements (if, elif, else)

Conditional statements are used to make decisions in your Python programs. You can perform different actions based on whether certain conditions are met. Python provides if, elif (short for "else if"), and else statements for this purpose.

1. The if Statement

The if statement allows you to execute a block of code if a condition is true. Here's the basic syntax:

if condition:
    # Code to be executed if the condition is True

For example:

x = 5
if x > 3:
    print("x is greater than 3")

If the condition after the if keyword is true, the indented code block below it is executed.

2. The elif Statement

The elif statement is used to check additional conditions if the initial if condition is false. It allows you to provide multiple conditions to be evaluated in sequence. Here's the syntax:

if condition1:
    # Code to be executed if condition1 is True
elif condition2:
    # Code to be executed if condition2 is True

For example:

x = 2
if x > 5:
    print("x is greater than 5")
elif x > 2:
    print("x is greater than 2 but not greater than 5")

In this example, the second condition is checked only if the first condition is false.

3. The else Statement

The else statement is used to execute a block of code when none of the previous conditions are true. It doesn't have a condition of its own but is associated with the preceding if or elif statements. Here's the syntax:

if condition:
    # Code to be executed if the condition is True
else:
    # Code to be executed if the condition is False

For example:

x = 1
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

In this case, the code in the else block is executed because the initial condition is false.

4. Nested Conditionals

You can nest conditional statements within each other to handle more complex scenarios. For example:

x = 10
if x > 5:
    if x < 15:
        print("x is between 5 and 15")
    else:
        print("x is greater than or equal to 15")
else:
    print("x is not greater than 5")

This nested structure allows you to create more intricate logic based on multiple conditions.

Conditional statements are fundamental for controlling the flow of your Python programs. They help you execute specific code blocks based on the evaluation of conditions. In the following sections, we'll explore additional features and techniques for working with conditional statements.