If-else syntax

The if-else statement is a fundamental control structure that allows you to execute certain code blocks based on specific conditions. Here’s a detailed breakdown of how it works:

Basic if-else Syntax

The basic syntax for an if-else statement is as follows:

if condition:
    # block of code executed if the condition is true
else:
    # block of code executed if the condition is false

Explanation

  • if condition:: This line checks if the condition evaluates to True. If it does, the indented block of code following the if statement is executed.
  • else:: If the condition in the if statement evaluates to False, the code block following the else statement is executed instead.

Example

x = 10

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

Output:

x is greater than 5

elif Clause

You can use the elif (short for “else if”) clause to check multiple conditions sequentially. The elif clause comes after the if statement and before the else statement, if present. Here’s the syntax:

if condition1:
    # block of code executed if condition1 is true
elif condition2:
    # block of code executed if condition2 is true
else:
    # block of code executed if both condition1 and condition2 are false

Example

x = 15

if x > 20:
    print("x is greater than 20")
elif x > 10:
    print("x is greater than 10 but not greater than 20")
else:
    print("x is 10 or less")

Output:

x is greater than 10 but not greater than 20

Nested if Statements

You can nest if statements within each other to create more complex conditional logic.

Example

x = 10
y = 20

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

Output:

x is greater than 5 and y is greater than 15

Using Logical Operators

You can use logical operators (and, or, not) to combine multiple conditions within an if statement.

Example

x = 10
y = 20

if x > 5 and y > 15:
    print("x is greater than 5 and y is greater than 15")
else:
    print("One or both conditions are not met")

Output:

x is greater than 5 and y is greater than 15

Summary

  • The if statement checks a condition and executes the associated block if the condition is True.
  • The else statement executes a block of code if the if condition is False.
  • The elif statement allows you to check multiple conditions in sequence.
  • You can nest if statements and use logical operators to create more complex conditions.