Sagar Bhatia | 01 Aug, 2024

Python Conditional Statements

In programming, efficient decision-making constructs are essential for crafting robust applications. This article delves into practical implementations of switch-case structures across different programming languages. By examining examples in Python and C++, readers understand how to leverage these constructs to enhance code readability and functionality.

Python Conditional Statements

The different types of statements in Python and their explanations are given below:

If Statement

The ‘if’ statement is used for decision-making. Once the constraints are defined, it will run the body of the code only when ‘If’ statement is true.

Basic Syntax:

if expression
statement

Example:

a, b = 11, 32

if a < b:
    qw = "a is less than b"
    print(qw)

Try It Yourself »

If-Else Statement

This statement comes in when the If condition is not met. The If-Else statement provides and If statement and an Else statement.

Basic Syntax:

If expression
statement

else
statement

Example:

a, b = 11, 32

if a < b:
    qw = "a is less than b"
else:
    qw = "b is less than a"

print(qw)

Try It Yourself »

Else-If (elif) Statement

The Else-If statement is used when the else condition might not suffice. This is used mostly in those cases when you have to justify more than two results.

Basic Syntax:

If expression
statement

elif expression
statement

else
statement

Example:

def main():
    q, r = 3, 3
    if q < r:
        yz = "q is less than r"
    elif q == r:
        yz = "q is same as r"
    else:
        yz = "q is greater than r"
    print(yz)

# Call the main function
main()

Try It Yourself »

Nested Else-If Statement

The nested Else-If statement is used when there are multiple results need to be defined.

Basic Syntax:

If expression
statement
elif expression
statement
elif expression
statement
elif expression
statement
.
.
.
else
statement

Example:

Cost = 125
country = "IN"

if Cost <= 50:
    print("Shipping Cost is 25")
elif Cost <= 100:
    print("Shipping Cost is 10")
elif Cost <= 150:
    print("Shipping Cost is 5")
else:
    print("FREE")

Try It Yourself »

Switch Statement

A switch case statement is a multi-branched statement that compares the value of a variable to the values specified in the cases. Python does not have a switch statement but it can be implemented using other methods, which will be discussed below.

To do this in Python, we use a dictionary.

def my_function(argument):
    switcher = {
        0: "This is Case Zero",
        1: "This is Case One",
        2: "This is Case Two"
    }
    return switcher.get(argument, "nothing")

# Example usage
print(my_function(0))  # Output: This is Case Zero
print(my_function(1))  # Output: This is Case One
print(my_function(2))  # Output: This is Case Two
print(my_function(3))  # Output: nothing

Try It Yourself »

The Switch Case Statement

In general computer programming and associated languages, the switch case statement is a form of selection means to alter the control flow of program execution through the value of a predefined variable or expression, using the process of search and select. The switch statement is to some extent similar to the if statement, which is used in a variety of programming languages, including C, C++, Visual Basic, Python, Pascal and Java. Many variations of the statement are used in other languages, with names such as case, inspect or select.

In the majority of languages, the typical syntax of the switch case statement is as follows:

  • First the control expression is defined, upon which the switch statement is implemented
  • Successive lines defining the case values and subsequent statements which will be executed in case of a match
  • An ending declaration to conclude the said statement

Implementation of Switch Case in Python

Unlike many other languages, Python does not have a default switch construct.

This may feel odd if you are from a Java or C++ background, but in Python, Switch needs to be implemented in a roundabout way, rather than directly. To get around this, one would need to use the pre-built dictionary construct of Python to define the cases and the outcome, if and when a case is met.

Below we take an example, where we will define a function month() to tell us a certain month of the year. The dictionary performing the mapping in this is called switcher.

Full Code in Python

def month(i):
    switcher = {
        1: 'January',
        2: 'February',
        3: 'March',
        4: 'April',
        5: 'May',
        6: 'June',
        7: 'July',
        8: 'August',
        9: 'September',
        10: 'October',
        11: 'November', 
        12: 'December'
    }
    return switcher.get(i, "Invalid month of the year")

# Example usage
print(month(1))  # Output: January
print(month(11))  # Output: November
print(month(13))  # Output: Invalid month of the year

Try It Yourself »

As you can see, the switcher will only print out the values provided, and will return a ‘Invalid month of the year’ when another value is input. It happens as it was told to do so using the get() method of a dictionary.

To implement the switch case in Python, we can also use

  • Python Functions & Lambdas
  • Python Classes

Python Functions & lambdas

Switch case can be implemented in Python using Python functions & lambdas, the syntax of which is given below:

def zero():
    return 'zero'

def one():
    return 'one'

def example(i):
    switcher = {
        0: zero,
        1: one,
        2: lambda: 'two'
    }
    func = switcher.get(i, lambda: 'Invalid')
    return func()

# Example usage
print(example(0))  # Output: zero
print(example(1))  # Output: one
print(example(2))  # Output: two
print(example(3))  # Output: Invalid

Try It Yourself »

When different values are passed through it, we get:

>>> example(7)
‘Invalid’
>>> example(1)
'one'
>>> example(3.12)
'Invalid'

Python Classes

Using the concept of Classes, we can implement Switch case with the following syntax:

class Switcher(object):
    def example(self, i):
        method_name = 'number_' + str(i)
        method = getattr(self, method_name, lambda: 'Invalid')
        return method()

    def number_0(self):
        return 'zero'

    def number_1(self):
        return 'one'

    def number_2(self):
        return 'two'

# Example usage
switcher = Switcher()
print(switcher.example(0))  # Output: zero
print(switcher.example(1))  # Output: one
print(switcher.example(2))  # Output: two
print(switcher.example(3))  # Output: Invalid

Try It Yourself »

When different values are passed through it, we get:

>>> s=Switcher()
>>> s.exampe(2)
'two'
>>> s.example(1.2)
'Invalid'
>>> s.number_1()
'one'

Switch Case vs If Else

In computer programming, both ‘if-else’ and ‘switch’ statements are selection statements. A selection statement will alter the flow of the program to the specific set of statements depending upon the nature of the condition, which is either ‘true’ or ‘false’. The fundamental difference between the if-else and switch statement is that the if-else statement will select the execution of the statements on the basis of the evaluation of the expressions in the if statements, while the switch statement selects the execution of the statement on the basis of the keyboard command.

Implementation in other languages

If-Else

The if-else is a selection statement in object-oriented programming. Below is the general form of an if-statement:

if (stated expression) {
statement (X)
} else {
statement (Y)
}

Here, both ‘if’ and ‘else’ are keywords, and the above-mentioned statements can either be a single statement or a set of statements. In the if statement, the expression can be an integer, character, pointer, floating-point or Boolean type. If the expression returns ‘true’, the statement(s) inside if will be executed, otherwise, the statement(s) inside the else is executed.

Let us understand better with an example:

i, j = 1, 2

if i == 1 and j == 2:
    print("Yes")
else:
    print("No")

Try It Yourself »

Since the expression is true, the output will be ‘Yes’

Switch

As discussed above, the Switch statement is basically a multiple-choice selection statement. The general form of a switch statement is given below:

switch( expression ){
case constant1:
statement(s);
break;
case constant2:
statement(s);
break;
case constant3:
statement(s);
break;
.
.
default
statement(s);
}

The expression above will only check for equality and nothing else. The expression will be confirmed against the constants in the case statements and if a match is found, the statement associated with the case will be executed, up until a ‘break’ is defined.

As the break statement is not obligatory in case statements, the execution will not stop till the end of the statement if a break is missing. Here is an example of a switch statement executed in C++:

#include <iostream>
using namespace std;

int main() {
    int i;
    cout << "Choose a value from 1 to 3: ";
    cin >> i;

    switch (i) {
        case 1:
            cout << "You chose Red";
            break;
        case 2:
            cout << "You chose Blue";
            break;
        case 3:
            cout << "You chose Orange";
            break;
        default:
            cout << "You chose nothing";
            break;
    }

    return 0;
}

In the above code, the value of i decides which case will be executed through the value provided by the user. If the user gives a value other than 1,2 and 3, the default case will be executed.

Comparison between If-Else and Switch Case Statements

Comparison Parameter Switch Case If-Else
Execution The user decides which statement will be executed The output of the expression inside the if statements will decide which statement is executed
Evaluation Switch statements can only evaluate character or integer value If-Else statements can evaluate integer, character, pointer, floating-point and Boolean types
Test The switch statement tests for equality The If-Else statement tests for equality and logical expression
Expression A single expression is used for multiple choices Multiples statements are used for multiple choices
Sequence of Execution Either the if statement is executed or the else statement The switch statement will execute one case after another until a break occurs or the end of the statement is reached
Default Case If the input value does not match any of the cases inside the switch statement, then the default case is executed If the expression inside the if statement is false, then by default the else statement is executed
Ease of Editing Editing switch case statements is easy due to cleaner code and easily recognizable cases If nested if-else is used, editing the statements might be a hassle

Conclusion

This is everything you should know about the Python Switch Case statement and conditional statements. If you're looking for a deeper dive, check out one of these Python courses

If you have any questions regarding the Python Switch Case Statement or have a suggestion to make, feel free to do so via the  comments section below.

People are also reading:

By Sagar Bhatia

Sagar is an engineering graduate and a technology lover and has been writing across various disciplines for over 5 years now. An avid gamer himself, he wishes to create a venture revolving around the e-sports domain in India.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments