There is no switch statement in Python, but there are equivalents depending on what you want to achieve. The best-known use of switch is to evaluate a value and avoid nesting multiple if statements.

Today I will explain it: how to make an equivalent switch in Python.

When you want to evaluate a sentence with multiple conditions

You can observe the most common case when you want to compare the value of an element with multiple conditions.

For example, give the user the option they want, and evaluate depending on it:

That is a switch in a universe where Python incorporates it, however, it does not currently exist. Therefore, the code should be as follows:

Maybe at the beginning it is a bit cumbersome, but the equivalent to switch in Python are many if statements, with elif (which means else if) and else, which is the default case.

Use switch to get a value

Another use of switch in Python is when you want to get a value of a function from an argument that can have multiple values. For example, get the name of the day from its number; taking Sunday as 0, Monday as 1 and finally Saturday as 6.

For this, the first thing you think is to write a function as follows:

It’s okay, and it uses the switch equivalent in Python, but it can be written in a better way:

In this way, a dictionary and its get method are used, which receives the key of the value to be obtained (something like the index) and the default value in case the key does not exist.

Conclusion

In conclusion there is no switch statement in Python, but there are equivalents for all cases. In fact, you could say that switch is syntactic sugar for if.

¿Encontraste lo que buscabas?

Si es así, suscríbete para que estés enterado de mis nuevos posts sobre programación e informática

Estoy interesado en trabajar contigo de manera remota para llevar tu idea a la realidad, formar parte de tu equipo de desarrolladores, ayudarte con tu tarea, dar asesorías y todo lo relacionado con tecnología y programación. Contáctame para más información
No te vayas sin seguirme en Twitter, Facebook y GitHub
Si tienes dudas déjalas en un comentario, pero asegúrate de seguirme antes como agradecimiento (no te cuesta nada y me ayudas mucho)


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
%d bloggers like this: