switch Statements
In this lesson, we will learn all about switch statements, their use, and syntax.
We'll cover the following
What are switch
statements?
A switch
statement is a unique conditional statement that allows a variable to be tested for equality against a list of values. Each value is called a case
.
The variable is checked for each case.
switch
Statements basically provide decision making capability: choose an option corresponding to the expression. The options are chosen based on two criteria of the options:
-
Based on Index – Choose the option whose index corresponds to the value of the expression.
-
Based on Matching Value - Choose the option which is an exact match of the expression.
The code flow of switch statement can be represented using the following illustration.
Let’s dive right into the syntax and implementation.
Syntax
switch(expression, case1, case2, case3....)
# Here, the "expression" parameter determines which case to choose from.
switch(2, "circle", "square", "triangle")
In the above code, the expression directs the program to choose the second option.
Let’s have a look at some more examples:
In the code snippet below, we use the variable input
that contains the index of the case we want to select.
input = 3output = switch(input, "Morning", "Afternoon", "Evening", "Night")print(output)
In the code snippet below, we use the variable input
that contains the exact matching value of the case we want to select. In this case, the compiler matches the value and returns the object associated with it.
input = "E"output = switch(input, "M" = "Morning","A" = "Afternoon","E" = "Evening","N" = "Night")print(output)