Python - Conditional Statements

13.
Discuss the concept of truthy and falsy values in Python conditional statements.

In Python, values are considered either truthy or falsy when used in conditional statements. Truthy values are treated as True, while falsy values are treated as False.

Here's an example program illustrating truthy and falsy values:

# Example program

# Truthy values
if 1:
    print("1 is truthy")

if "Hello":
    print("Hello is truthy")

if [1, 2, 3]:
    print("List is truthy")

# Falsy values
if 0:
    print("0 is falsy")
else:
    print("0 is falsy")

if "":
    print("Empty string is falsy")
else:
    print("Empty string is falsy")

if []:
    print("Empty list is falsy")
else:
    print("Empty list is falsy")
1 is truthy
Hello is truthy
List is truthy
0 is falsy
Empty string is falsy
Empty list is falsy

In this example:

  • Values like 1, 'Hello', and [1, 2, 3] are truthy, and the corresponding if statements print messages indicating truthiness.
  • Values like 0, '' (empty string), and [] (empty list) are falsy, and the corresponding else statements print messages indicating falsiness.

Understanding truthy and falsy values is essential for writing effective conditional statements in Python.


14.
How do you handle exceptions using thetry, except, else, and finally blocks in Python?

In Python, exception handling is done using the try, except, else, and finally blocks. The try block contains the code that may raise an exception, and the except block contains the code to handle the exception.

Here's an example program illustrating the usage of these blocks:

# Example program

def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Division by zero is not allowed")
    else:
        print(f"Result: {result}")
    finally:
        print("This block always executes")

# Example usage
divide_numbers(10, 2)
divide_numbers(5, 0)
Result: 5.0
Error: Division by zero is not allowed
This block always executes

In this example:

  • The divide_numbers function attempts to divide two numbers. If the division is successful, the else block is executed and prints the result. If a ZeroDivisionError occurs, the except block is executed, handling the exception.
  • The finally block always executes, regardless of whether an exception occurred or not.

This structure allows you to gracefully handle exceptions and ensure that certain code (in the finally block) runs regardless of whether an exception occurred or not.


15.
Explain the use of the in and not in operators in Python conditional statements.

The in and not in operators in Python are used to check whether a value is present in a sequence (such as a string, list, or tuple) or not.

Here's an example program illustrating the usage of these operators:

# Example program

# Using 'in' operator
fruits = ['apple', 'orange', 'banana']
if 'apple' in fruits:
    print("Apple is present in the list")
else:
    print("Apple is not present in the list")

# Using 'not in' operator
colors = ('red', 'green', 'blue')
if 'yellow' not in colors:
    print("Yellow is not present in the tuple")
else:
    print("Yellow is present in the tuple")
Apple is present in the list
Yellow is not present in the tuple

In this example:

  • The in operator is used to check if 'apple' is present in the fruits list.
  • The not in operator is used to check if 'yellow' is not present in the colors tuple.

These operators are useful for conditional statements where you want to test the membership of a value in a sequence or its absence.


16.
What is the purpose of the break and continue statements in loop structures within conditional statements?

In Python, the break and continue statements are used within loop structures to alter the flow of the loop based on certain conditions.

Here's an example program illustrating the use of break and continue statements within a while loop:

# Example program

# Using 'break' and 'continue' in a while loop
i = 0
while i < 5:
    i += 1
    if i == 3:
        print("Skipping iteration for i =", i)
        continue  # Skip the rest of the loop body and move to the next iteration
    print("Inside the loop for i =", i)
    if i == 4:
        print("Breaking out of the loop for i =", i)
        break  # Exit the loop when i is 4
Inside the loop for i = 1
Inside the loop for i = 2
Skipping iteration for i = 3
Inside the loop for i = 4
Breaking out of the loop for i = 4

In this example:

  • The continue statement is used to skip the rest of the loop body when i is equal to 3.
  • The break statement is used to exit the loop when i is equal to 4.

These statements provide flexibility in controlling the execution of loops based on certain conditions, making the code more efficient and readable.