3.1 Conditional Statements (if, elif, else)

Conditional statements are used to control the flow of a program by executing specific blocks of code based on certain conditions. In Python, the primary conditional statements are if, elif, and else, which allow you to make decisions and execute code selectively. In this section, we'll explore how these conditional statements work and how you can use them to add logic to your programs.


3.1.1 The if Statement

The if statement is used to check a condition, and if the condition evaluates to True, the block of code inside the if statement is executed.

Syntax:

if condition:
    # Code to execute if condition is True

The condition is usually a Boolean expression (an expression that evaluates to True or False).

Example 1:

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

Output:

x is greater than 5

In this example, the condition x > 5 evaluates to True, so the code inside the if block is executed.

Example 2 (False Condition):

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

In this case, since x > 5 is False, the code inside the if block will not be executed, and nothing is printed.


3.1.2 The else Statement

The else statement is used to define a block of code that will run if the condition in the if statement evaluates to False. It acts as a fallback option when the if condition is not met.

Syntax:

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

Example:

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

Output:

x is not greater than 5

Here, the condition x > 5 is False, so the code inside the else block is executed.


3.1.3 The elif Statement

The elif (short for "else if") statement allows you to check multiple conditions in sequence. If the first if condition is False, Python moves on to check the elif conditions. You can have multiple elif statements to test for different conditions.

Syntax:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if all conditions are False

Example:

x = 7
if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but less than or equal to 10")
else:
    print("x is 5 or less")

Output:

x is greater than 5 but less than or equal to 10

Here’s how this works:

  1. Python checks if x > 10. Since this is False, it moves on to the elif condition.
  2. It checks if x > 5. Since this is True, the corresponding block is executed.
  3. The else block is skipped because the elif condition was True.

3.1.4 Nested Conditional Statements

You can nest if, elif, and else statements inside one another to check multiple conditions more precisely. However, nesting too deeply can make the code harder to read, so it's usually better to keep it simple when possible.

Example:

x = 10
y = 5

if x > 5:
    if y > 3:
        print("x is greater than 5 and y is greater than 3")
    else:
        print("x is greater than 5 but y is not greater than 3")
else:
    print("x is not greater than 5")

Output:

x is greater than 5 and y is greater than 3

Here, we first check if x > 5. If this is True, we then check the nested condition y > 3.


3.1.5 Logical Operators in Conditional Statements

You can combine multiple conditions using logical operators (and, or, not) in a single if, elif, or else statement.

Example with and:

x = 7
y = 10

if x > 5 and y > 5:
    print("Both x and y are greater than 5")

Output:

Both x and y are greater than 5

The and operator requires both conditions to be True for the block to execute.

Example with or:

x = 3
y = 8

if x > 5 or y > 5:
    print("At least one of x or y is greater than 5")

Output:

At least one of x or y is greater than 5

The or operator allows the block to execute if at least one of the conditions is True.

Example with not:

x = 5

if not x > 10:
    print("x is not greater than 10")

Output:

x is not greater than 10

The not operator inverts the result of the condition, so if x > 10 is False, not x > 10 will be True.


3.1.6 Conditional Expressions (Ternary Operator)

Python also supports a shorthand way of writing simple if-else statements using conditional expressions (also known as the ternary operator).

Syntax:

value_if_true if condition else value_if_false

Example:

x = 10
result = "Greater than 5" if x > 5 else "5 or less"
print(result)  # Output: Greater than 5

Here, the expression "Greater than 5" if x > 5 else "5 or less" checks if x is greater than 5. If the condition is True, the value "Greater than 5" is returned; otherwise, "5 or less" is returned.


3.1.7 Common Mistakes with Conditional Statements

Using Assignment Instead of Comparison:
Be careful not to confuse the assignment operator (=) with the equality operator (==).

x = 5
if x = 5:  # SyntaxError: invalid syntax
    print("x is 5")

The correct version:

if x == 5:
    print("x is 5")

Missing Indentation:
Each block of code following if, elif, or else must be indented.

x = 10
if x > 5:
print("x is greater than 5")  # IndentationError

The correct version:

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

3.1.8 Summary

  • The if statement executes a block of code if a condition is True.
  • The else statement provides a fallback option, executing a block of code if the if condition is False.
  • The elif statement allows you to check additional conditions if the first if statement is False.
  • You can use logical operators (and, or, not) to combine multiple conditions.
  • Nested if statements can be used for more complex conditions, but it's best to avoid excessive nesting to keep the code readable.
  • Conditional expressions (ternary operators) provide a shorthand way of writing simple if-else conditions.

Mastering conditional statements is crucial for writing logic-driven Python programs that make decisions and control the flow based on user input or other conditions.