Switch

Switch Statement in Computer Programming

A switch statement is a control structure used in programming to allow the execution of different code blocks based on the value of a variable or expression. It acts as a simpler way to write a sequence of if-else statements by directly comparing the value of an expression with multiple possible cases and executing the corresponding block of code.

Python Example

Python doesn't have a built-in switch statement, but you can simulate it using dictionaries. Here's a simple example:

def switch_example(value):
    switcher = {
        1: "One",
        2: "Two",
        3: "Three",
    }
    return switcher.get(value, "Invalid number")

print(switch_example(2))  # Output: Two

C# Example

C# has a switch statement, making it much more straightforward. Here's how you use it:

using System;

class Program
{
    static void Main()
    {
        int number = 2;
        switch (number)
        {
            case 1:
                Console.WriteLine("One");
                break;
            case 2:
                Console.WriteLine("Two");
                break;
            case 3:
                Console.WriteLine("Three");
                break;
            default:
                Console.WriteLine("Invalid number");
                break;
        }
    }
}

In both examples, the code determines the output based on the value of the number or value variable by matching it with the cases defined in the switch structure, allowing for cleaner and more readable code compared to multiple if-else statements.

Last updated

Was this helpful?