Comment on page
Switch / Case
Use a
Switch
or Case
statement if you are going to have many else if
statements or the condition is not inherently boolean in nature (like the value of a string, for example).C++, Java, and Javascript
Python
Simple Example
More Examples
Same syntax for C++, Java, Javascript, and many other languages.
switch(expression) {
case value :
// Code to run
break; // optional to break out of the switch block
case value :
// Code to run
break; // optional to break out of the switch block
/** You can have any number of case statements. **/
default : // Optional case to catch any other possibilities
// Code to run
}
Python does not have a Switch / Case implementation. Instead, you use something called a
dictionary
and call it a switcher
. You can read more about that on your own:An example of switching (in this example, we are switching on a user's input):
// Javascript
let userInput = prompt("Please enter a colour", "blue");
switch (userInput) {
case "red":
// code for what happens when user enters red
break;
case "blue":
// code for what happens when user enters blue
break;
case "black":
// code for what happens when user enters black
break;
case "yellow":
// code for what happens when user enters yellow
break;
default:
// code for what happens when user enters anything else
}
Rather than reinventing the wheel, here are some other sites with great content on this topic:
The following example creates a random number from 1-10 (inclusive) and decides what to do based on that number. The random number is just a way of faking user input or a value from some other function. The example does something specific for numbers 1, 2, 3, 7, and 9 but all the rest fall under the
default
case. You will need to scroll down in the example or open it in a new window due to the length.This example switches on text instead of a number. Same procedure as numbers, just a string instead. You might need to scroll the example or open it in a new window to see it better.
The
switch
statement is not used on boolean values. It is strictly meant for multiple options similar to a menu or list. General rule of thumb - when your code is a bunch of if...else if
statements, it might be better suited for a switch
statement unless you are using boolean operators (&& and ||).Last modified 5yr ago