If...Else...

Introduction:

  • Python supports logical conditions from mathematics:
    • Equals: a == b
    • Not Equals: a != b
    • Less than: a < b
    • Less than or equal to: a <= b
    • Greater than: a > b
    • Greater than or equal to: a >= b

Else Statement:

  • The else keyword catches anything not caught by preceding conditions.

Syntax of If-Else:

python
if boolean_expression:
    statement(s)
else:
    statement(s)
  • Indentation is crucial. Statements inside the if and else blocks must be properly indented.

Examples:

  1. If-Else with Condition True:

    python
    a = 2
    b = 4
    
    if a < b:
        print(a, 'is less than', b)
    else:
        print(a, 'is not less than', b)
    
    • Output: 2 is less than 4
  2. If-Else with Condition False:

    python
    a = 5
    b = 4
    
    if a < b:
        print(a, 'is less than', b)
    else:
        print(a, 'is not less than', b)
    
    • Output: 5 is not less than 4
  3. Nested If-Else:

    python
    a = 2
    b = 4
    c = 5
    
    if a < b:
        print(a, 'is less than', b)
        if c < b:
            print(c, 'is less than', b)
        else:
            print(c, 'is not less than', b)
    else:
        print(a, 'is not less than', b)
    
    • Output:

      2 is less than 4
      5 is not less than 4
      

Summary:

  • Python if-else statements are fundamental for controlling the flow of your program based on conditions. Practice writing if-else statements to become proficient in using conditional logic in your programs