IF - Else Statement in Python

 


The if-else statement in Python is a control flow structure that allows you to test a condition and execute one block of code if the condition is True and another block if the condition is False.

Syntax:

  • if condition:

  •     # Code block to execute if the condition is True

  • else:

  •     # Code block to execute if the condition is False


  • The condition is an expression that evaluates to either True or False.

  • If the condition is True, the code inside the if block runs.

  • If the condition is False, the code inside the else block runs.

Example 1: Basic if-else Statement

  • 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

In this example:

  • The condition x > 5 is True, so the if block is executed.

Example 2: if-else with a False Condition

  • 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

In this case:

  • The condition x > 5 is False, so the else block is executed.

Multiple if-else Statements (Chained if-else)

You can chain multiple if-else statements using elif (else if) to check for multiple conditions.

Syntax:

  • if condition1:

  •     # Code block to execute if condition1 is True

  • elif condition2:

  •     # Code block to execute if condition2 is True and condition1 is False

  • else:

  •     # Code block to execute if both conditions are False


Example 3: Using if-elif-else

  • x = 15


  • if x > 20:

  •     print("x is greater than 20")

  • elif x > 10:

  •     print("x is greater than 10 but less than or equal to 20")

  • else:

  •     print("x is 10 or less")


Output: x is greater than 10 but less than or equal to 20

In this case:

  • The first condition x > 20 is False, so it checks the next condition x > 10, which is True. Thus, the elif block is executed.

Example 4: Chained if-else for Different Ranges

  • age = 22


  • if age < 18:

  •     print("You are a minor.")

  • elif age < 60:

  •     print("You are an adult.")

  • else:

  •     print("You are a senior citizen.")


Output: You are an adult.

Key Points:

  • if is used to check a condition, and if it’s True, the associated block of code is executed.

  • else provides an alternative block of code that is executed if the condition is False.

  • elif allows you to check multiple conditions in a sequence (useful when you have more than two options to evaluate).

  • if-else statements are a fundamental tool for controlling program flow based on conditions.

Let me know if you'd like more examples or a deeper explanation! 😊


Post a Comment

0 Comments