Going back to the for cycle / Volviendo al ciclo for - Coding Basics Lite #2

Going back to the basics of for


w3resource4.png

Shoutout to w3resource

HiveDivider.png

In this article you will find:

  • Introduction
  • Presentation of the problem
  • Required functions and methods
  • Solving the Problem

HiveDivider.png

Good night all! Sorry for the time of publication. Currently I am still experiencing the after-effects of a stomach pain that has hit me hard. However, we are here to talk about programming and that is what we will do.

Sometimes we have to go back to the basics to understand how the most complex functions work. In this case, we revisit a very dear friend of the Python programmer: The For loop.

So, if you want to take the initiative and solve the problem yourself, I invite you to do so. However, if you want to know how I would solve it or see another method, just keep reading.

Without more to say,

Let's get started!
HiveDivider.png

Problem Presentation


TutLane.png

Shoutout to Tutlane

The problem will be something simple. We are asked to design a program which allows us to enter any text we want and give us the option of making all its characters uppercase or lowercase.

The requirements will be:

  • Allow user to insert text.
  • Allow the user to decide whether letters will be made uppercase or lowercase

Thus, we will have our points to take into account. You just need to start designing.

If you want to get started and do it, go ahead! If you want to see how I do it, just read the next section.

HiveDivider.png

What commands will we use?


IPCisco.jpg

Shoutout to IPCisco

By asking that we give the user freedom to write their commands, we already know that we must use input to enter any text. However, how will we make it upper or lower case. Easy, we just have to use the isupper() and islower() commands to check if the words in the text are uppercase or lowercase.

However, before we can determine if the words within the sentence are case-sensitive, we must insert them as a list. This is why we use the split() command for strings which does just this:

string1 = str(input('Write the text you want to convert: '))

listthat = string1.split()

Now, all that remains is to ask the user if they want all words to be made uppercase or lowercase with another input:

string1 = str(input('Write the text you want to convert: '))

listthat = string1.split()
lowup= str(input("Write Upper if you want to make all the words uppercase or lower If you want to make all the words lowercase: "))

Now that we have the list with the different words, it will be obvious that we must use the for loop to loop through each element and convert it to upper or lower case, which we will see in the next section

HiveDivider.png

Solving the problem


codingem.png

Shoutout to codingem.com

Once we use the flower cycle (Determining the words as an item in listthat), we must ask a series of questions.

The first will be: Should we make the text uppercase or lowercase? It is here that we place the first if and elif to determine lowup is lower or upper.

Then, all we have to do is nest another conditional and ask if the current word is upper/lower case with isupper() or islower().

string1 = str(input('Write the text you want to convert: '))

listthat = string1.split()
lowup= str(input("Write Upper if you want to make all the words uppercase or lower If you want to make all the words lowercase: "))

for item in listthat:
     if lowup == 'Lower' or lowup == 'lower':
         if item.islower() == False:
             print(item.lower(), end=' ')
         else:
             print(item, end=' ')
     elif lowup == 'Upper' or lowup == 'upper':
         if item.isupper() == False:
             print(item.upper(), end=' ')
         else:
             print(item, end=' ')

As we can see in this code, we ask if islower() is false for the word. If it is, we simply use lower() to convert it to lowercase, repeating the process until the for ends.

Note: end=" " is used to make the end of each line continue in a space, which causes the following words to be written next to each other.

Then, in case we have detected that a word is lowercase with islower(), we just have to print the word as such.

The opposite case will apply for upper, where if we have upper in lowup and we determine with isupper() that the word is not capitalized, we convert it with upper. If it is already a capital letter, it is printed as such.

And in this way, we will have a simple and functional program that will allow us to convert any text into upper or lower case.

HiveDivider.png

I hope you enjoyed this little example, where we went back to basics and created something that the beginner in us will always admire: Something of our own.

Don't worry if Coding Basics Regular was not published today, if it improves tomorrow (Which will be most likely), I will definitely return to complete the complete numpy tutorial so that you are not left behind.

I wish you a happy day, night or afternoon.

HiveDivider.png

Thank you for your support and good luck!

HiveDivider.png

@jesalmofficial.png

HiveDivider.png

Volviendo a los básicos del for


w3resource4.png

Shoutout to w3resource

HiveDivider.png

En este artículo encontrarás:

  • Introducción
  • Presentación del problema
  • Funciones y métodos requeridos
  • Resolviendo el Problema

HiveDivider.png

¡Buenas noches a todos! Disculpen la hora de publicación. Actualmente sigo experimentando las secuelas de un dolor de estómago que me ha golpeado duro. Sin embargo, estamos para hablar sobre programación y eso es lo que haremos.

A veces debemos de volver a lo básico para comprender como las funciones más complejas funcionan. En este caso, visitamos de nuevo a un amigo muy querido del programador en Python: El ciclo For.

Así, si quieres tomar la iniciativa y resolver el problema por ti mismo te invito a hacerlo. Sin embargo, si quieres saber como lo resolvería o ver otro método, solo debes de seguir leyendo.

Sin más que decir,

¡Comencemos!
HiveDivider.png

Presentación del Problema


TutLane.png

Shoutout to Tutlane

El problema será algo sencillo. Se nos pide que diseñemos un programa el cual nos permita ingresar cualquier texto que deseemos y darnos la opción de hacer todos sus caracteres mayúsculas o minúsculas.

Los requisitos serán:

  • Permitir al usuario insertar el texto.
  • Permitir al usuario decidir si las letras se harán mayúsculas o minúsculas

Así, ya tendremos nuestros puntos a tomar en cuenta. Solo falta empezar a diseñar.

Si quieres empezar y hacerlo, ¡Adelante! Si quieres ver como lo hago, solo lee la siguiente sección.

HiveDivider.png

¿Qué comandos usaremos?


IPCisco.jpg

Shoutout to IPCisco

Al pedir que le demos libertad al usuario de escribir sus comandos, ya sabemos que debemos de utilizar input para ingresar cualquier texto. Sin embargo, como haremos para hacerlo mayúscula o minúscula. Facil, solo debemos hacer uso de los comandos isupper() e islower() para verificar si las palabras del texto están en mayúscula o minúscula.

Sin embargo, antes de poder determinar si las palabras dentro de la oración son mayúsculas y minúsculas, debemos de insertar estas como una lista. Es por esto que usamos el comando split() para strings que hace justo esto:

string1 = str(input('Write the text you want to convert: '))

listthat = string1.split()

Ahora, solo quedará preguntar al usuario si quiere que se hagan todas las palabras mayúsculas o minúsculas con otro input:

string1 = str(input('Write the text you want to convert: '))

listthat = string1.split()
lowup= str(input("Write Upper if you want to make all the words uppercase or lower If you want to make all the words lowercase: "))

Ahora que tenemos la lista con las diferentes palabras, será obvio que debemso de usar el ciclo for para recorrer cada elemento y convertirlo en mayúscula o minúscula, lo cual veremos en la siguiente sección

HiveDivider.png

Resolviendo el problema


codingem.png

Shoutout to codingem.com

Una vez que usemos el ciclo flor (Determinando las palabras como item en listthat), debemos de realizar una serie de preguntas.

La primera será: ¿Debemos de hacer el texto mayúscula o minúscula? Es aquí que colocamos el primer if y elif para determinar lowup es lower o upper.

Entonces, solo nos queda anidar otro condicional y preguntar si la palabra actual está en mayúscula/minúscula con isupper() o islower().

string1 = str(input('Write the text you want to convert: '))

listthat = string1.split()
lowup= str(input("Write Upper if you want to make all the words uppercase or lower If you want to make all the words lowercase: "))

for item in listthat:
    if lowup == 'Lower' or lowup == 'lower':
        if item.islower() == False:
            print(item.lower(), end=' ')
        else:
            print(item, end=' ')
    elif lowup == 'Upper' or lowup == 'upper':
        if item.isupper() == False:
            print(item.upper(), end=' ')
        else:
            print(item, end=' ')

Como podemos ver en este código, preguntamos si islower() es false para la palabra. En caso de serlo, simplemente usamos lower() para convertirlo en minúscula, repitiendo el proceso hasta que el for termine.

Nota: end=" " es usado para que el final de cada línea continue en un espacio, lo que hace que las siguientes palabras se escriban una al lado de la otra.

Luego, en caso de que hayamos detectado que una palabra es minúscula con islower(), solo debemos de imprimir la palabra como tal.

El caso contrario aplicará para upper, donde si tenemos upper en lowup y determinamos con isupper() que la palabra no está en mayúscula, la convertimos con upper. En caso de que ya sea mayúscula, se imprime como tal.

Y de esta manera, tendremos un programa sencillo y funcional que nos permitirá convertir cualquier texto en mayúsculas o minúsculas.

HiveDivider.png

Espero que hayas disfrutado de este pequeño ejemplo, donde volvimos a lo básico y creamos algo que el principiante en nosotros siempre admirará: Algo propio.

No te preocupes si Coding Basics Regular no se publicó hoy, en caso de mejorar mañana (Que será lo más probable), volveré sin faltar a completar el tutorial completo de numpy para que no se queden atrás.

Les deseo un feliz día, noche o tarde.

HiveDivider.png

¡Gracias por tu apoyo y buena suerte!

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