if…else

We have seen truthy and falsy values earlier. We have also seen comparison operators like ==,<,<= etc which when used with operands, returns boolean(type ‘bool’) values. All these things evaluate to either True or False.

Anything that evaluates to give us a value are known as expressions. There are different types of expressions but we will be talking about boolean expressions at this point.

These all expressions can be evaluated to a boolean value. So, these all can be used as boolean expressions wherever necessary.

There are certain scenarios where we need to perform certain actions according to the truthiness or falsiness of an expression. In that case, we need something which will check the boolean expression and perform the necessary actions. For this, we have if statements in Python. the syntax of if statement is as follows:

if expression:

   statement

The statement will be executed only if the expression evaluates to True.

For example,

Here, the expression, 2<3 evaluates to True and that’s why Hello will be printed.

Let’s take another example,

Here, the expression 9<3 evaluates to False, so the Hello will not be printed.

Please note that there is an indentation before starting the print statement. This indentation indicates that the print statement is part of the if statement. Without this indentation, Python will throw an error.

Let us take another scenario where we want to perform a particular operation if the statement is True, and another operation if the expression is False. In that case, we need an else statement as well along with the if statement.

Here, the expression 9<3 evaluates to False, so the “Hello” will not be printed. Instead, the “Welcome” of the else statement will be printed.

These examples involve only a single condition. But in some cases, we may need to perform different actions for different conditions. For such cases, we can go with multiple if statements as follows:

We can also use match statements for such scenarios. For example,

Here, whichever case matches with the num value, the print statement of that particular case is executed.

We can also set a default case, which will be matched when no other cases match. It is denoted by _(underscore) as follows:

Interview Questions

Ans. A boolean expression is any expression in Python that evaluates to either True or False. Boolean expressions are the core of if statements, as the if statement checks the truthiness of the expression to decide whether to execute the code block under it. Examples include comparisons (2 < 3, 9 >= 5), variable checks (if x), and even function calls that return booleans.

Ans. Indentation is crucial in Python as it defines code blocks. In an if statement, the indented lines immediately following the if condition are considered part of the block that will be executed if the condition is True. Incorrect indentation can lead to errors, as Python may interpret the code differently than intended, potentially executing statements outside the if block when they should only be executed under certain conditions.

Ans. There are two primary ways to handle multiple conditions:

  1. Multiple if Statements: You can chain multiple if statements together. Each if statement’s condition is checked independently, and the corresponding block is executed if the condition is True.
  2. if-elif-else Chain: This structure allows you to test multiple conditions sequentially. If the first if condition is False, it moves to the next elif (else if) condition, and so on. The final else block is executed if none of the previous conditions are True.

Ans. The match statement is a pattern-matching construct. It can be used to concisely compare a variable against multiple possible values (cases) and execute the code block associated with the matching case. It’s often more readable and maintainable than a series of if-elif-else statements when you have multiple discrete values to compare. The _ (underscore) can be used as a default case to handle situations where none of the other cases match.

Coding Problems

Ans. 

num = 5  # You can change this value to test different numbers

if num > 0:

    print(“Positive”)

else:

    print(“Not Positive”) 

Ans.

num = 2  # Change this value to test different cases

match num:

    case 1:

        print(“One”)

    case 2:

        print(“Two”)

    case 3:

        print(“Three”)

    case _: 

        print(“Number is not 1, 2, or 3”)

Ans. 

age = 20  # Replace with the actual age

if age >= 18:

    print(“Eligible to vote”)

else:

    print(“Not eligible to vote”)

Ans.

num = int(input(“Enter a number: “))  

if num % 2 == 0:

    print(“Even”)

else:

    print(“Odd”)

Code snippet based problems

x = 10

y = 5

if x > y:

    result = “Greater”

else:

    result = “Not Greater”

print(result)

Ans. The output will be “Greater”. This is because the if condition (x > y) is True (10 is greater than 5), so the code inside the if block will execute, assigning “Greater” to the variable result.

temperature = 25

if temperature > 30:

    print(“It’s hot!”)

elif temperature > 20:

    print(“It’s pleasant.”)

else:

    print(“It’s cool.”)

Ans.  The output will be “It’s pleasant.” The first condition (temperature > 30) is not met, so it moves to the elif condition (temperature > 20), which is True. The code in that block is executed, and the rest of the conditions are not checked.

num = 7

match num % 2:  

    case 0:

        print(“Even”)

    case 1:

        print(“Odd”)

Ans. This code uses a match statement to check if a number is even or odd. It takes the remainder of num divided by 2 (num % 2). If the remainder is 0, it prints “Even”; otherwise (if the remainder is 1), it prints “Odd”. Since 7 leaves a remainder of 1 when divided by 2, the output will be “Odd”.

Q. 

is_raining = True

have_umbrella = False

if is_raining:

    if have_umbrella:

        print(“Take the umbrella!”)

    else:

        print(“Wait for the rain to stop.”)

else:

    print(“Enjoy the sunny day!”)

Analyze the code and explain what output you would expect if:

a) is_raining is True and have_umbrella is True.

b) is_raining is True and have_umbrella is False.

c) is_raining is False.

Ans. 

a) If is_raining is True and have_umbrella is True, the output will be: “Take the umbrella!”

b) If is_raining is True and have_umbrella is False, the output will be: “Wait for the rain to stop.”

c) If is_raining is False, the output will be: “Enjoy the sunny day!”

Q. What is the purpose of the elif statements in this code, and how do they contribute to determining the final grade?

score = 85

if score >= 90:

    grade = “A”

elif score >= 80:

    grade = “B”

elif score >= 70:

    grade = “C”

else:

    grade = “D”

print(“Your grade is:”, grade)

Ans. The elif statements allow for testing multiple conditions sequentially. In this code, they help determine the grade based on a range of scores. If the first condition (score >= 90) isn’t met, it checks the next elif (score >= 80), and so on. The final else block acts as a default if none of the above conditions are true. In this case, since the score is 85, the second elif condition is met, and the grade “B” is assigned.

Q. 

hour = 15  # 24-hour format

match hour:

    case hour if hour < 12:

        print(“Good morning!”)

    case hour if 12 <= hour < 18:

        print(“Good afternoon!”)

    case _:

        print(“Good evening!”)

Explain how the match statement and conditional guards (if) work together to determine the appropriate greeting based on the hour.

Ans. The match statement compares hour against the different cases. Each case has a conditional guard (e.g., hour if hour < 12) that is evaluated if the main case matches. The first case with a True guard will be executed.

  • If hour is less than 12, it matches the first case, and the guard is True, so “Good morning!” is printed.
  • If hour is 12 or greater but less than 18, it matches the second case, and its guard is True, so “Good afternoon!” is printed.
  • For any other value of hour, the default case (_) is matched, and “Good evening!” is printed.