Python - Conditional Statements

17.
How can you use the assert statement for debugging in Python?

The assert statement in Python is used for debugging purposes. It checks if a given expression is True, and if not, it raises an AssertionError exception with an optional error message.

Here's an example program illustrating the use of the assert statement for debugging:

# Example program

# Using 'assert' for debugging
def divide(a, b):
    assert b != 0, "Cannot divide by zero"  # Check if 'b' is not zero
    return a / b

# Test cases
result1 = divide(10, 2)
print("Result 1:", result1)

result2 = divide(8, 0)  # This will raise an AssertionError
print("Result 2:", result2)
Result 1: 5.0
Traceback (most recent call last):
  File "example.py", line 11, in 
    result2 = divide(8, 0)
  File "example.py", line 5, in divide
    assert b != 0, "Cannot divide by zero"
AssertionError: Cannot divide by zero

In this example:

  • The assert statement is used to check if b is not zero before performing division.
  • The first division (divide(10, 2)) is successful, and the result is printed.
  • The second division (divide(8, 0)) raises an AssertionError because dividing by zero is not allowed. The error message is also displayed.

Using assert statements can help identify and fix issues during development by quickly highlighting unexpected conditions.


18.
Explain the concept of short-circuit evaluation in Python conditional statements.

In Python conditional statements, short-circuit evaluation is a behavior where the second operand of a logical expression is evaluated only if the first operand does not determine the outcome.

Here's an example program illustrating short-circuit evaluation:

# Example program

# Using short-circuit evaluation
def is_positive(x):
    return x > 0

def is_even(x):
    return x % 2 == 0

# Short-circuit 'and' evaluation
result_and = is_positive(5) and is_even(4)
print("Result (and):", result_and)

# Short-circuit 'or' evaluation
result_or = is_positive(-2) or is_even(6)
print("Result (or):", result_or)
Result (and): False
Result (or): True

In this example:

  • The function is_positive returns True if the given number is positive.
  • The function is_even returns True if the given number is even.
  • Short-circuit 'and' evaluation: is_positive(5) is True, but is_even(4) is not evaluated because the first operand already determines the result as False.
  • Short-circuit 'or' evaluation: is_positive(-2) is True, and is_even(6) is not evaluated because the first operand already determines the result as True.

Short-circuit evaluation can be beneficial for efficiency, especially when the second operand involves a costly operation that can be skipped if the first operand is sufficient to determine the overall result.


19.
How do you use the switch case statement in Python?

Python doesn't have a native switch statement like some other programming languages. However, you can achieve similar functionality using a dictionary and functions or lambda expressions. Here's an example:

# Example program with a "switch" using a dictionary

def case1():
    return "This is case 1."

def case2():
    return "This is case 2."

def case3():
    return "This is case 3."

def default_case():
    return "This is the default case."

def switch_case(case_number):
    switch_dict = {
        1: case1,
        2: case2,
        3: case3
    }

    # Use get() to handle default case
    selected_case = switch_dict.get(case_number, default_case)
    return selected_case()

# Test cases
result1 = switch_case(1)
result2 = switch_case(2)
result3 = switch_case(3)
result_default = switch_case(5)

print(result1)
print(result2)
print(result3)
print(result_default)
This is case 1.
This is case 2.
This is case 3.
This is the default case.

In this example:

  • We define functions case1, case2, case3, and default_case to represent different cases and the default case.
  • The switch_case function takes a case_number as an argument and uses a dictionary (switch_dict) to map case numbers to corresponding functions.
  • The get() method is used to retrieve the function for a specific case. If the case is not found in the dictionary, it defaults to the default_case function.
  • We then call the selected function to get the result for the corresponding case.

While this approach simulates a switch-like behavior, keep in mind that Python's approach to handling such situations typically involves using if/elif/else statements or dictionaries.


20.
Discuss the differences between theif statement and the if expression (PEP 308) in Python.

In Python, the if statement and the if expression (ternary conditional expression) serve different purposes, although both are used for conditional execution. Let's discuss each and provide examples.

1. if Statement:

# Example of an if statement
x = 10

if x > 5:
    result = "x is greater than 5"
else:
    result = "x is not greater than 5"

print(result)
x is greater than 5

In this example, the if statement checks whether x is greater than 5. If the condition is true, it executes the code block under the if branch; otherwise, it executes the code block under the else branch.

2. if Expression (PEP 308):


# Example of an if expression
x = 10

result = "x is greater than 5" if x > 5 else "x is not greater than 5"

print(result)
x is greater than 5

In this example, the if expression provides a more concise way to achieve the same result as the if statement. The syntax is a if condition else b, and it evaluates to a if the condition is true, otherwise b.

The key differences are:

  • if statement allows for more complex logic and multiple statements in each branch.
  • if expression is more concise and often used when the result is a simple expression.
  • if expression evaluates both a and b, while the if statement only executes the block corresponding to the true condition.