switch newPost{case upvote_if_you_like:}
In this article you'll find:
- Introduction
- What is a Switch Statement?
- What does a Switch statement look like in code?
- A little example
A few days ago, I talked about conditionals, statements that allowed us to execute different instructions depending on whether a condition was met or not. This seemed to be a perfect solution when working with code with different possible outcomes.
However, this became complicated if the number of conditions increased. Let's say we want to create a conditional that tells us what grade A through F we got on a test. The code would look like this.
if grade == "A":
print("Your grade is A")
elif grade == "B":
print("Your grade is B")
elif grade == "C":
print("Your grade is C")
elif grade == "D":
print("Your grade is D")
elif grade == "E":
print("Your grade is E")
elif grade == "F":
print("Your grade is F")
else:
print("Did you ever made the test?")
This can be really confusing and redundant for the person reading it. Therefore, we have an alternative instruction that we can use in many languages, which allows us to set different cases with only two keywords: switch and case.
If you want to do the wording of a result with different conditions, look no further than this article.
Let's get started!
What is a switch statement?
According to our old friend Wikipedia:
A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Enough with the rocket science. In simple terms, a switch statement is basically a conditional If (More on this here), which allows us to execute different instructions depending on a case.
Now, what makes it different from the If, is that we don't have to use cumbersome statements like elif and else, always declaring different conditions and taking up more code space than we should.
It does this by determining different cases for each scenario, cases that if fulfilled, will cause particular instructions to be executed. If we look at the following flowchart:
And if we make an example where we verify the ID of each person and, depending on the age, we let them pass or not, we will have the following:
Now that we know how it works, what does a switch statement look like when written in code?
What does a switch statement look like in code?
Depending on the programming language, a switch statement can have different forms. However, they all operate under the same precepts. If we consider a syntax made in C:
switch(expression) {
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
We see that it is easy to understand. Inside the switch we place the variable or expression from which we want to evaluate the result. Then, in case, we place different possible results for that variable and the instructions that are executed according to each result. Finally, we place break to end the instruction and the switch.
Note: break is optional in some languages and mandatory in others. Whenever there is the possibility of placing it, it is good practice to do so.
However, if we consider Python, this language did not have the option to make switch statements until recently. It was not until Python 3.10 that a match-case control selection structure was added. This is identical to switch-case, changing only the keyword switch for match. Looking at its syntax:
match parameter:
case first :
do_something(first)
case second :
do_something(second)
case third :
do_something(third)
.............
............
case n :
do_something(n)
case _ :
nothing_matched_function()
Another peculiarity that we can notice in Python is that we should not use break, because Python knows when to stop the switch/match. Also, instead of putting default, we would put case _ for values outside the expected cases.
To finish understanding the switch/match statements, we will see an example in C and Python that will clarify our doubts.
A little example
We have a directory with different streets and we want verbal instructions on how to get there. How do we do this with switch? For this, we first define our variable where we will place the desired street.
street = ## Here you put the number of the street.
or, in C:
char street = "";
Now, we will consider three possible streets: Washington St, Madison St and Hamilton St. To define this in Python, we use:
match street:
case "Washington St":
print("Turn right, then left, then down two blocks")
case "Madison St":
print("Turn left, then go south and turn right in the first traffic light")
case "Hamilton St":
print("Keep going until you see a traffic light, then, you are on Hamilton St")
case _:
print("I don't know that address")
Or, in C:
switch(street)
{
case "Washington St":
printf("Turn right, then left, then down two blocks");
break;
case "Madison St":
printf("Turn left, then go south and turn right in the first traffic light");
break;
case "Hamilton St":
printf("Keep going until you see a traffic light, then, you are on Hamilton St");
break;
default:
printf("I don't know that address");
break;
}
Thus, if we assign to the Street the value of "Washington St" we will have as output:
>>> Turn right, then left, then down two blocks
Switch statements are a simple alternative that will make the task of determining different results for varying conditions less arduous to write.
Thus, with what you have learned, you will be able to master switch/match and increase your arsenal of tools, so that you can attack programs in different ways and demonstrate your mastery.
Thanks for your support and good luck!
switch newPost{case upvote_if_you_like:}
En este artículo encontrarás
- Introducción
- ¿Qué es una declaración Switch?
- ¿Como luce una declaración Switch en código?
- Un pequeño ejemplo
Hace unos días atrás, hablé sobre los condicionales, statements que nos permitían ejecutar distintas instrucciones dependiendo de si una condición se cumplía o no. Esto parecía ser una solución perfecta al trabajar con código con distintos resultados posibles.
Sin embargo, esto se complicaba si el número de condiciones aumentaba. Digamos que queremos crear un condicional que nos diga cual calificación de A hasta F tenemos en una examen. El código se vería de la siguiente manera.
if grade == "A":
print("Your grade is A")
elif grade == "B":
print("Your grade is B")
elif grade == "C":
print("Your grade is C")
elif grade == "D":
print("Your grade is D")
elif grade == "E":
print("Your grade is E")
elif grade == "F":
print("Your grade is F")
else:
print("Did you ever made the test?")
Esto puede ser realmente confuso y redundante para la persona que lo lee. Por eso, tenemos una instrucción alternativa que podemos usar en gran cantidad de lenguajes, la cual nos permite establecer distintos casos con solo dos keywords: switch y case.
Si quieres hacer la redacción de un resultado con distintas condiciones, no mires más lejos que este artículo.
¡Comencemos!
¿Qué es una declaración Switch?
Según nuestra vieja amiga Wikipedia
Una sentencia switch es un tipo de mecanismo de control de selección utilizado para permitir que el valor de una variable o expresión cambie el flujo de control de la ejecución del programa a través de search y map.
Basta de ciencia de cohetes. En términos simples, una sentencia switch es básicamente un If condicional (Más sobre esto aquí), que nos permite ejecutar diferentes instrucciones dependiendo de un caso.
Ahora bien, lo que lo diferencia del If, es que no tenemos que usar engorrosas sentencias como elif y else, declarando siempre diferentes condiciones y ocupando más espacio de código del que deberíamos.
Esto lo hace determinando diferentes casos para cada escenario, casos que si se cumplen, harán que se ejecuten determinadas instrucciones. Si nos fijamos en el siguiente diagrama de flujo:
Y si hacemos un ejemplo donde verifiquemos la ID de cada persona y, dependiendo de la edad, los dejamos pasar o no, tendremos los siguiente:
Ahora que sabemos como funciona, ¿Como se ve una declaración switch al escribirla en código?
¿Como luce una declaración Switch en código?
Dependiendo del lenguaje de programación, una sentencia switch puede tener diferentes formas. Sin embargo, todas operan bajo los mismos preceptos. Si consideramos una sintaxis hecha en C:
switch(expresión) {
case expresión-constante :
expresión(s);
break
case expresión-constante :
statement(s);
break;
/* puede tener cualquier número de sentencias case */
default : /* Opcional */
sentencia(s);
}
Vemos que es fácil de entender. Dentro del switch colocamos la variable o expresión de la que queremos evaluar el resultado. Luego, en case, colocamos los diferentes resultados posibles para esa variable y las instrucciones que se ejecutan según cada resultado. Por último, colocamos break para finalizar la instrucción y el switch.
Nota: break es opcional en algunos lenguajes y obligatorio en otros. Siempre que exista la posibilidad de colocarlo, es una buena práctica hacerlo.
Sin embargo, si consideramos Python, este lenguaje no tuvo la opción de hacer sentencias switch hasta hace poco. No fue hasta Python 3.10 que se añadió una estructura de selección de control match-case. Ésta es idéntica a switch-case, cambiando únicamente la palabra clave switch por match. Mirando su sintaxis:
match parameter:
case first :
do_something(first)
case second :
do_something(second)
case third :
do_something(third)
.............
............
case n :
do_something(n)
case _ :
nothing_matched_function()
Otra peculiaridad que podemos notar en Python es que no debemos usar break, porque Python sabe cuando parar el switch/match. Además, en lugar de poner default, pondríamos case _ para valores fuera de los casos esperados.
Para terminar de entender la declaraciones switch/match, veremos un ejemplo en C y Python que clarificará nuestras dudas.
Un pequeño ejemplo
Tenemos un directorio con distintas calles y queremos instrucciones verbales sobre como llegar. ¿Como hacemos esto con switch? Para esto, definimos primero nuestra variable donde colocaremos la calle deseada.
street = ## Here you put the number of the street.
o, en C:
char street = "";
Ahora, tendremos en cuenta tres posibles calles: Washington St, Madison St y Hamilton St. Para definir esto en python, usamos:
match street:
case "Washington St":
print("Turn right, then left, then down two blocks")
case "Madison St":
print("Turn left, then go south and turn right in the first traffic light")
case "Hamilton St":
print("Keep going until you see a traffic light, then, you are on Hamilton St")
case _:
print("I don't know that address")
Y en C:
switch(street)
{
case "Washington St":
printf("Turn right, then left, then down two blocks");
break;
case "Madison St":
printf("Turn left, then go south and turn right in the first traffic light");
break;
case "Hamilton St":
printf("Keep going until you see a traffic light, then, you are on Hamilton St");
break;
default:
printf("I don't know that address");
break;
}
De esta forma, si le asignamos al Street el valor de "Washington St" tendremos como salida:
>>> Turn right, then left, then down two blocks
Las declaraciones switch son una alternativa sencilla que hará que la labor de determinar distintos resultados para condiciones que varían sea una labor menos ardua de escribir.
Así, con lo aprendido, podrás dominar los switch/match y aumentarás tu arsenal de herramientas, para poder atacar programas de distintas formas y así demostrar tu maestría.
Gracias por tu apoyo y ¡Buena suerte!