If Else Statement in Python

In Python, the if, else, and elif (short for "else if") statements are used for conditional execution of code. These statements allow you to execute different blocks of code based on whether certain conditions are true or false. Here's a basic overview of how the If Else Statement in Python work:

pythonCopy codeif condition1:
    # Block of code to execute if condition1 is True
elif condition2:
    # Block of code to execute if condition1 is False and condition2 is True
else:
    # Block of code to execute if both condition1 and condition2 are False
  • if: This is the initial condition that is checked. If it evaluates to True, the associated block of code is executed. If it evaluates to False, the next condition (elif or else) is checked.

  • elif (optional): Short for "else if". It allows you to check multiple conditions. If the preceding if or elif conditions are False and the elif condition is True, the associated block of code is executed.

  • else (optional): This block of code is executed if none of the preceding conditions (if or elif) are True.

Here's an example demonstrating the usage of if, elif, and else statements in Python:

pythonCopy codex = 10

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

Output:

vbnetCopy codex is equal to 10

In this example:

  • x is equal to 10, so the condition x == 10 is True.

  • Therefore, the block of code associated with the elif statement is executed, printing "x is equal to 10".

  • The else block is not executed because the condition associated with it (x < 10) is False. Check out online Python Interpreter to practice and excel in your tech career!