Match Case Horoscope / Horóscopo con Match Case - Coding Basics Lite #4

VIEWING THE HOROSCOPE


CPPSECRETS.png

Shoutout to CPPSECRETS

HiveDivider.png

In this article you will find

  • Introduction
  • Problem Presentation
  • Required Knowledge
  • Resolving the Problem

HiveDivider.png

Greetings to all!

In this edition of Coding Basics Lite we will refresh our knowledge about a conditional that gives us a great advantage when choosing between a large number of conditions: The match case.

In this exercise, we will test how much we remember about using match case (Python's version of switch case).

If you want to remember how to use match-case to your advantage, just keep reading.

Let's get started!

HiveDivider.png

Problem Presentation


EnglishJagran.jpg

Shoutout to English Jagran

This problem will be somewhat simple. For this, we will have to design a program that asks us for our horoscope sign and based on that, returns our horoscope prediction for that day. In this case, the only condition will be to apply the Match-Case as conditional.

In this way, we already know all the details of this example. Some may not remember how match-case works. We will see this in the next section.

HiveDivider.png

Required Knowledge


Match Case.png

Shoutout to Towards Data Science

In this case, the knowledge required will be how to create a variable that asks us for its value with a message. Because we usually use it quite frequently, we know that the input will be used, which requests the information and asks us for a message that we will enter as a parameter. Also, since we only want string values, we put str before it.

The most important thing will be the match-case, since with this we can determine the different conditions and what type of message will be shown if each one is met. The syntax in Python will be the following:

match var_name:
case var_value1:
## Here you write the code to be executed if the condition is met / Here you write the code to be executed if the condition is met.
``` case var_value2:
##Code
case var_value3:
##Code
.
.
.
case_:
# The code that is executed If no condition from the list is met / The code that is executed if any of the conditions in the list are not met.

We can see that the keyword will be match, where the name of the variable to which we want to apply the conditional is placed next to it. Then, with case we establish each of the possible conditions and within these we write the code that will be executed if they are met.

Lastly, the case _: is usually used so that if any of the conditions are not met we can execute alternative code.

Now that we know how to use the Match-Case, it's time to put it into practice.

HiveDivider.png

Solving the problem

image.png

As we know, we will first use the input to create a variable that asks us for our zodiac sign. Since words will be written, we must check that the information is only a string. This is why we use str, to convert the information entered into a string if possible.

var_sign = str(input('Insert your horoscope sign: '))

Then, we use match taking this variable as the object to which the conditional will be applied. However, because the sign can write all lowercase, all uppercase, or a combination of both, we use lower(), the method that allows us to convert the uppercase letters of a string to lowercase, to take only the necessary information:

match var_sign.lower():

Then each possible scenario starts, we use case 'aquarius', so it checks if aquarius was written in var_sign. If 'taurus' is written, we use case 'taurus':, repeating this for each sign

match var_sign.lower():
    case 'aquarius':
        print('If you\'re looking for romance, keep in mind that not all relationships start off as sizzling affairs. Many of the healthiest and longest-lasting start at a slow and steady simmer. Instead of looking for lightning to strike, just keep an eye out for people who seem interesting to you. Then put in the time it takes to get to know them better. If you aren\'t looking for romance, be aware that someone could be looking for romance with you!')
    case 'aries':
        print('Be prepared for a few scheduling hiccups today. Suddenly, an unforeseen event could limit your free time and make you feel a little like you\'re under the gun. But have no fear! This rapid change of pace won\'t send you down a stressful path. Instead, it will be invigorating and bring out your competitive nature. This can be a fun day full of twists and turns that keep you on the edge of your seat and ready for the next curve ball to come your way!')
    case 'cancer':
        print('Your external world and internal world are at odds right now. You have great ideas, but you\'re not interested in shouting them out to the world. Something is keeping you introverted right now, and you need to just sit with it until it\'s over and you\'re ready to break out of your shell again. This is a perfectly normal phase to be going through, so don\'t add stress to your life by worrying about it. Being alone might bring you comfort right now, and that\'s all that matters.')
    case 'capricorn':
        print('You\'ve been attracting flighty people lately, and while it\'s been fun, it has also been fairly frustrating. Today, it would do you good to take a break from the people who always seem to cancel on you at the last minute. Call up one or two of the people you know you can always count on and find out when you can get together next. You don\'t have to cut your ties with the people who are driving you nuts right now, though. Variety is the spice of life and of friendships.')
    case 'gemini':
        print('Today, you can get a lot more out of listening and learning than you can from getting a laugh, enjoying a flirtatious conversation, or relaxing with a friend. It\'s a serious day with serious rewards if you\'re willing to put in the energy required to earn them. Moving away from instant gratification might make you feel like you\'re depriving yourself at first, but you\'ll soon realize that once you\'ve fed your mind, you\'ll be that much better at knowing how to feed your soul.')
    case 'leo':
        print('If you\'re feeling bored with the same faces in your group of friends, maybe it\'s time to look to the past for your social future. Dig out your contact list and refresh your memory about friends who you\'ve let slip away, either through life changes or job changes. You\'ll soon remember at least one cool person, and the chances are good that they\'d love to hear from you. Give them a call and see what\'s new in their life. Set a date and your boredom is cured!')
    case 'libra':
        print('If you aren\'t in the mood to be social right now, the worst thing you could do would be to force yourself to go out. You can\'t convince yourself to have a good time if you\'re just not feeling it. When you pretend you\'re having fun, you won\'t be fooling anyone. Your acting skills just aren\'t that great right now. But even though you\'re not into hanging out with others, you\'ll still have some good energy. You\'ll just be able to enjoy it more alone.')
    case 'pisces':
        print('A few last-minute changes might be required of you today, especially if you\'re going to be traveling or you\'re about to embark on a trip. The good news is that your brain is sharp and firing on all cylinders, and you\'ll be able to adapt and ride whatever waves come along. In fact, you\'ll get quite an ego boost out of being able to handle with grace and aplomb the twists and turns that the day throws at you. People will be amazed and impressed.')
    case 'sagittarius':
        print('Today, absolutely anything is possible. This day is a blank slate, and it\'s up to you to draw the picture you want to see. The outcome of anything you\'re involved in is totally up to you. The amount of energy and value you put into things is going to dictate the amount of energy and value that you get out of them. Get serious and be willing to work a little harder and a little longer if need be. The blank canvas won\'t intimidate you. It will excite you!')
    case 'scorpio':
        print('Today, other people\'s money could cause you to think more about your own money. Either you don\'t have as much as someone else and want more, or you have so much more than someone else that you\'re feeling guilty. Either way, you can\'t let money come between you and a friend. Social plans should be organized with that in mind. Don\'t expect a struggling friend to be comfortable going out on the town in first-class style. There are many ways to have fun without spending a dime, so start with some of those.')
    case 'taurus':
        print('Someone is suddenly seeing you in a brand-new light today, and it could trigger some deeper conversations. No longer will the two of you waste time in small talk. You\'re both ready to get to the heart of the matter and get things resolved. You can\'t expect them to reach out to you, so be prepared to do some of the work first. Ask for some of their time and request some wise advice. This is a wonderful opportunity to show them that you care about what they think.')
    case 'virgo':
        print('When you enter a new group situation today, try not to be as socially cautious as you often are. There\'s no need to be intimidated. A little quick reasoning will tell you that you have plenty of things in common with these people, so if you\'re at a loss for what to talk about, start there. Conversation is an art, but you have your own special twist on it. Don\'t be afraid to strike up conversations today. People will be more receptive than you think.')
    case _:
        print('This isn\'t a horoscope sign')

Here we can see that the code that will be printed if any of the conditions are met is then entered, and _, if none of the conditions are met. Now that we have all this covered, all that remains is to execute:

>>>
Insert your horoscope sign: Taurus
Someone is suddenly seeing you in a brand-new light today, and it could trigger some deeper conversations. No longer will the two of you waste time in small talk. You're both ready to get to the heart of the matter and get things resolved. You can't expect them to reach out to you, so be prepared to do some of the work first. Ask for some of their time and request some wise advice. This is a wonderful opportunity to show them that you care about what they think.

And so, we can verify that we have a program for the horoscope.

HiveDivider.png

I hope that this example, although short, can help you remember the value of a tool as valuable as match-case, allowing us to save lines of code that we would otherwise spend on if, elif and else. I encourage you to use this in more examples than the one shown. If you feel comfortable, you could even send some here.

This way, you never stop creating and learning. See you in the next editions of Coding Basics and Coding Basics Lite.

HiveDivider.png

Thank you for your support and good luck!

HiveDivider.png

@jesalmofficial.png

HiveDivider.png

VIENDO EL HORÓSCOPO


CPPSECRETS.png

Shoutout to CPPSECRETS

HiveDivider.png

En este artículo encontrarás

  • Introducción
  • Presentación del Problema
  • Conocimiento Requerido
  • Resolviendo del Problema

HiveDivider.png

¡Un saludo a todos!

En esta edición de Coding basics Lite refrescaremos nuestro conocimiento sobre un condicional que nos brinda una gran ventaja a la hora de escoger entre una gran cantidad de condiciones: El match case.

En este ejercicio, pondremos a prueba cuanto recordamos sobre el uso de match case (La versión de switch case en Python).

Si quieres recordar como usar match-case a tu favor, solo tienes que seguir leyendo.

¡Comencemos!

HiveDivider.png

Presentación del Problema


EnglishJagran.jpg

Shoutout to English Jagran

Este problema será algo sencillo. Para este, tendremos que diseñar un programa que nos pida nuestro signo del horoscopo y en base a eso devolvernos nuestra predicción del horóscopo para ese día. En este caso, la única condición será el aplicar como condicional el Match-Case.

De esta forma, ya conocemos todos los detalles de este ejemplo. Puede que algunos no recuerden como funciona el match-case. Veremos esto en la siguiente sección.

HiveDivider.png

Conocimientos Requeridos


Match Case.png

Shoutout to Towards Data Science

En este caso, los conocimientos requeridos será l de como crear una variable que nos pida su valor con un mensaje. Debido a que solemos usarla con bastante frecuencia, sabemos que se usará el input, el cual nos solicita la información y nos pide un mensaje que introduciremos como parámetro. Además, como solo queremos valores string, colocamos str antes de esta.

Lo más importante será el match-case, ya que con este podremos determinar las distintas condiciones y que tipo de mensaje se mostrará en caso de que se cumpla cada una. La sintaxis en Python será la siguiente:

match var_name:
    case var_value1:
        ## Here you write the code to be executed if the condition is met / Aquí escribes el código a ser ejecutado si la condición se cumple.
``` case var_value2:
        ## Code
    case var_value3:
        ## Code
    .
    .
    .
    case _:
        # The code that is executed If no condition from the list is met / El código que se ejecuta si no se cumple alguna de las condiciones de la lista.

Podemos ver que la palabra clave será match, dond se coloca al lado el nombre de la variable a la que queremos aplicar el condicional. Luego, con case establecemos cada una de las condiciones posibles y dentro de estas escribimos el código que se ejecutara si se cumplen.

Se suele usar por último el case _: para que en caso de que no se cumpla alguna de las condiciones podamos ejecutar código alternativo.

Ahora que sabemos como se usa el Match-Case, es tiempo de ponerlo en práctica.
HiveDivider.png

Resolviendo el problema

image.png

Como sabemos, primero usaremos el input para crear una variable que nos pida nuestro signo zodiacal. Ya que se escribirán palabras, debemos de comprobar que la información solo sea una string. Es por esto que usamos str, para convertir la información introducida en string en caso de poderse.

var_sign = str(input('Insert your horoscope sign: '))

Luego, usamos el match tomando esta variable como el objeto al que se aplicar el condicional. Sin embargo, debido a que el signo puede escribir todo en minúsculas, todo en mayúsculas o una combinación de ambas, usamos lower(), el método que nos permite convetir las letras mayúsculas de una string en minúsculas, para tomar solo la información necesaria:

match var_sign.lower():

Luego, comienza cada posible escenario, usamos case 'aquarius', para que verifique si se escribió aquarius en var_sign. Si se escribe 'taurus', usamos case 'taurus':, repitiendo esto para cada signo

match var_sign.lower():
    case 'aquarius':
        print('If you\'re looking for romance, keep in mind that not all relationships start off as sizzling affairs. Many of the healthiest and longest-lasting start at a slow and steady simmer. Instead of looking for lightning to strike, just keep an eye out for people who seem interesting to you. Then put in the time it takes to get to know them better. If you aren\'t looking for romance, be aware that someone could be looking for romance with you!')
    case 'aries':
        print('Be prepared for a few scheduling hiccups today. Suddenly, an unforeseen event could limit your free time and make you feel a little like you\'re under the gun. But have no fear! This rapid change of pace won\'t send you down a stressful path. Instead, it will be invigorating and bring out your competitive nature. This can be a fun day full of twists and turns that keep you on the edge of your seat and ready for the next curve ball to come your way!')
    case 'cancer':
        print('Your external world and internal world are at odds right now. You have great ideas, but you\'re not interested in shouting them out to the world. Something is keeping you introverted right now, and you need to just sit with it until it\'s over and you\'re ready to break out of your shell again. This is a perfectly normal phase to be going through, so don\'t add stress to your life by worrying about it. Being alone might bring you comfort right now, and that\'s all that matters.')
    case 'capricorn':
        print('You\'ve been attracting flighty people lately, and while it\'s been fun, it has also been fairly frustrating. Today, it would do you good to take a break from the people who always seem to cancel on you at the last minute. Call up one or two of the people you know you can always count on and find out when you can get together next. You don\'t have to cut your ties with the people who are driving you nuts right now, though. Variety is the spice of life and of friendships.')
    case 'gemini':
        print('Today, you can get a lot more out of listening and learning than you can from getting a laugh, enjoying a flirtatious conversation, or relaxing with a friend. It\'s a serious day with serious rewards if you\'re willing to put in the energy required to earn them. Moving away from instant gratification might make you feel like you\'re depriving yourself at first, but you\'ll soon realize that once you\'ve fed your mind, you\'ll be that much better at knowing how to feed your soul.')
    case 'leo':
        print('If you\'re feeling bored with the same faces in your group of friends, maybe it\'s time to look to the past for your social future. Dig out your contact list and refresh your memory about friends who you\'ve let slip away, either through life changes or job changes. You\'ll soon remember at least one cool person, and the chances are good that they\'d love to hear from you. Give them a call and see what\'s new in their life. Set a date and your boredom is cured!')
    case 'libra':
        print('If you aren\'t in the mood to be social right now, the worst thing you could do would be to force yourself to go out. You can\'t convince yourself to have a good time if you\'re just not feeling it. When you pretend you\'re having fun, you won\'t be fooling anyone. Your acting skills just aren\'t that great right now. But even though you\'re not into hanging out with others, you\'ll still have some good energy. You\'ll just be able to enjoy it more alone.')
    case 'pisces':
        print('A few last-minute changes might be required of you today, especially if you\'re going to be traveling or you\'re about to embark on a trip. The good news is that your brain is sharp and firing on all cylinders, and you\'ll be able to adapt and ride whatever waves come along. In fact, you\'ll get quite an ego boost out of being able to handle with grace and aplomb the twists and turns that the day throws at you. People will be amazed and impressed.')
    case 'sagittarius':
        print('Today, absolutely anything is possible. This day is a blank slate, and it\'s up to you to draw the picture you want to see. The outcome of anything you\'re involved in is totally up to you. The amount of energy and value you put into things is going to dictate the amount of energy and value that you get out of them. Get serious and be willing to work a little harder and a little longer if need be. The blank canvas won\'t intimidate you. It will excite you!')
    case 'scorpio':
        print('Today, other people\'s money could cause you to think more about your own money. Either you don\'t have as much as someone else and want more, or you have so much more than someone else that you\'re feeling guilty. Either way, you can\'t let money come between you and a friend. Social plans should be organized with that in mind. Don\'t expect a struggling friend to be comfortable going out on the town in first-class style. There are many ways to have fun without spending a dime, so start with some of those.')
    case 'taurus':
        print('Someone is suddenly seeing you in a brand-new light today, and it could trigger some deeper conversations. No longer will the two of you waste time in small talk. You\'re both ready to get to the heart of the matter and get things resolved. You can\'t expect them to reach out to you, so be prepared to do some of the work first. Ask for some of their time and request some wise advice. This is a wonderful opportunity to show them that you care about what they think.')
    case 'virgo':
        print('When you enter a new group situation today, try not to be as socially cautious as you often are. There\'s no need to be intimidated. A little quick reasoning will tell you that you have plenty of things in common with these people, so if you\'re at a loss for what to talk about, start there. Conversation is an art, but you have your own special twist on it. Don\'t be afraid to strike up conversations today. People will be more receptive than you think.')
    case _:
        print('This isn\'t a horoscope sign')

Aquí podemos ver que se introduce después el código que se imprimirá en caso de que se cumpla alguna de las condiciones y _, en caso de que ninguna se cumpla. Ahora que tenemos todo esto cubierto, solo queda ejecutar:

>>>
Insert your horoscope sign: Taurus
Someone is suddenly seeing you in a brand-new light today, and it could trigger some deeper conversations. No longer will the two of you waste time in small talk. You're both ready to get to the heart of the matter and get things resolved. You can't expect them to reach out to you, so be prepared to do some of the work first. Ask for some of their time and request some wise advice. This is a wonderful opportunity to show them that you care about what they think.

Y así, podremos comprobar que tenemos un programa para el horóscopo.

HiveDivider.png

Espero que este ejemplo, aunque corto, pueda servirte de ayuda para recordar el valor de una herramienta tan valiosa como el match-case, permitiéndonos ahorrar líneas de código que de otra forma gastaríamos en if, elif y else. Te animo a usar esto en más ejemplos que el mostrado. Si te sientes cómodo, incluso podrías mandar alguno por aquí.

De esta forma, nunca dejes de crear y de aprender. Nos vemos en las siguientes ediciones de Coding Basics y Coding Basics Lite.

HiveDivider.png

Thank you for your support and good luck!

HiveDivider.png

@jesalmofficial.png



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000