Python IF, ELSE, ELIF, Nested IF & Switch Case Statement

Created with Sketch.

In Python, conditional statements like if, else, elif are used for decision-making, and there is no explicit switch statement. Here are examples of how to use these conditional statements:

1. if, else:

x = 10

if x > 0:
    print("x is positive.")
else:
    print("x is non-positive.")

2. if, elif, else (Multiple conditions):

score = 75

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'D'

print(f"Your grade is {grade}.")

3. Nested if:

 
x = 5
y = 10

if x > 0:
    print("x is positive.")
    
    if y > 0:
        print("y is also positive.")
    else:
        print("y is non-positive.")
else:
    print("x is non-positive.")

4. Switch-like behavior using dictionaries:

Although there’s no explicit switch statement in Python, you can use dictionaries to achieve a similar effect:

def switch_case(case):
    switch_dict = {
        'case1': "This is Case 1",
        'case2': "This is Case 2",
        'case3': "This is Case 3",
    }
    
    result = switch_dict.get(case, "This is the default case.")
    print(result)

# Example usage:
switch_case('case2')

In this example, get is used to retrieve the value associated with the specified key (case). If the key is not found, it returns a default value.

These examples cover the basic usage of if, else, elif, nested if, and a workaround for achieving switch-like behavior using dictionaries in Python. Choose the appropriate construct based on the complexity and readability of your code.

Leave a Reply

Your email address will not be published. Required fields are marked *