if-elif python

Conditional Statements in Python

In real-life scenarios, we often make decisions based on certain conditions. The same concept applies to programming—sometimes we want certain parts of the code to execute only if specific conditions are met. In Python, we use conditional statements to control this flow.

Python provides the following conditional statements:

  1. if

  2. if...else

  3. nested if

  4. if...elif...else

Let’s explore each of them:


1. if Statement

The if statement allows you to execute a block of code only when a condition is True.

Syntax:

if condition: # Code to execute if condition is True

Example:

# if statement example if 10 > 5: print("10 is greater than 5") print("Program ended")

Output:

10 is greater than 5 Program ended

👀Note: In Python, indentation (whitespace) is used to define blocks of code.


2. if...else Statement

The if...else statement lets you execute one block of code if a condition is True, and another block if it is False.

Syntax:

if condition: # Executes if condition is True else: # Executes if condition is False

Example 1:

# if...else statement example x = 3 if x == 4: print("Yes") else: print("No")

Output:

No

Example 2 (Chained if...else):

# if...else chain example letter = "A" if letter == "B": print("Letter is B") else: if letter == "C": print("Letter is C") else: if letter == "A": print("Letter is A") else: print("Letter isn't A, B, or C")

Output:

Letter is A

3. Nested if Statement

You can place an if statement inside another if statement. This is called a nested if statement and allows for checking multiple levels of conditions.

Syntax:

if condition1: # Executes when condition1 is True if condition2: # Executes when condition2 is True

Example:

# Nested if example num = 10 if num > 5: print("Bigger than 5") if num <= 15: print("Between 5 and 15")

Output:

Bigger than 5 Between 5 and 15

4. if...elif...else Statement

The if...elif...else statement is a cleaner way to write multiple conditions. It is an alternative to writing long chains of nested if...else statements.

Syntax:

if condition1: # Executes if condition1 is True elif condition2: # Executes if condition2 is True elif condition3: # Executes if condition3 is True else: # Executes if none of the above conditions are True

Example:

# if...elif...else example letter = "A" if letter == "B": print("Letter is B") elif letter == "C": print("Letter is C") elif letter == "A": print("Letter is A") else: print("Letter isn't A, B, or C")

Output:

Letter is A

Summary

  • Use if to execute code when a condition is True.
  • Use if...else to handle both True and False cases.
  • Use nested if when you need to check multiple conditions in layers.
  • Use if...elif...else when you have multiple mutually exclusive conditions.

Popular Posts