Control Flow: Conditionals (if, else, elif)

Understand how to control the flow of execution using conditional statements like 'if', 'else', and 'elif'.


Python Control Flow: Conditionals

In Python, control flow refers to the order in which statements are executed. Conditional statements (if, else, and elif) allow you to execute different blocks of code based on whether a condition is true or false. This allows your program to make decisions and respond to different inputs or situations.

The if Statement

The if statement is the most basic conditional statement. It executes a block of code only if a specified condition is true.

 if condition:
        # Code to execute if the condition is true 

Example:

 age = 20

    if age >= 18:
        print("You are an adult.") 

In this example, the condition age >= 18 is evaluated. Since age is 20, the condition is true, and the message "You are an adult." is printed.

The else Statement

The else statement is used in conjunction with the if statement. It provides a block of code to execute if the if condition is false.

 if condition:
        # Code to execute if the condition is true
    else:
        # Code to execute if the condition is false 

Example:

 age = 15

    if age >= 18:
        print("You are an adult.")
    else:
        print("You are a minor.") 

In this example, the condition age >= 18 is false because age is 15. Therefore, the code within the else block is executed, and the message "You are a minor." is printed.

The elif Statement

The elif (short for "else if") statement allows you to check multiple conditions in sequence. It's placed between the if and else statements. Only one of the blocks (either the if, one of the elif, or the else) will execute.

 if condition1:
        # Code to execute if condition1 is true
    elif condition2:
        # Code to execute if condition1 is false and condition2 is true
    elif condition3:
        # Code to execute if condition1 and condition2 are false, and condition3 is true
    else:
        # Code to execute if all conditions are false 

Example:

 score = 75

    if score >= 90:
        print("Excellent!")
    elif score >= 80:
        print("Good!")
    elif score >= 70:
        print("Okay")
    else:
        print("Needs improvement.") 

In this example, the conditions are checked in order. Since score is 75, the first two conditions (score >= 90 and score >= 80) are false. However, the third condition (score >= 70) is true, so the message "Okay" is printed.

Important Notes:

  • The condition in an if, elif, or else statement must evaluate to a boolean value (True or False).
  • You can use comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not) to create complex conditions.
  • The else statement is optional. You can have an if statement without an else or elif.
  • The elif statement is also optional. You can have an if statement with no elif statements.
  • The code within each block must be indented. Indentation is crucial in Python to define the scope of the block.

Complex Conditions

You can combine multiple conditions using logical operators:

  • and: Returns True if both conditions are true.
  • or: Returns True if at least one condition is true.
  • not: Negates a condition (returns True if the condition is false, and vice versa).

Example:

 age = 25
    has_license = True

    if age >= 18 and has_license:
        print("You are eligible to drive.")
    else:
        print("You are not eligible to drive.") 

In this case, both age >= 18 and has_license are true, so the condition age >= 18 and has_license is true, and the message "You are eligible to drive." is printed.

Nesting Conditionals

You can nest if statements inside other if, elif, or else statements to create more complex decision-making structures. However, deeply nested conditionals can become difficult to read and maintain, so consider simplifying your logic if possible.

 x = 10
    y = 5

    if x > 0:
        if y > 0:
            print("Both x and y are positive.")
        else:
            print("x is positive, but y is not.")
    else:
        print("x is not positive.") 

This example demonstrates nested if statements to check if both x and y are positive.