While Loops / Ciclos While - Coding Basics #4 [EN/ES]

in StemSocial2 years ago

while people_like_it == True:
keep_posting = True


WhileLoop.webp

Shoutout to and Real Python

HiveDivider.png

In this article you'll find:

  • Introduction
  • What is a while loop?
  • What do while loops look like in code
  • While Loop Statements
  • A little example

HiveDivider.png

In this edition of Coding Basics, we will continue with the cycles. In the previous chapter we talked about for cycles and their usefulness when working with iterable objects such as lists, dictionaries or even strings, where we already know the maximum number of elements.

However, what if we only want a loop to run as long as a condition is met? Let's say you want to create a program that searches for content on the Internet, all while you have an Internet connection. For this, we use the while loop.

So, if you are curious about how the while loop works or want to refresh your knowledge, this is the right place. With nothing more to say.

Let's get started!

HiveDivider.png

What is a while loop?


1200px-Do-while-loop-diagram.svg.png

Shoutout to Wikipedia.com

According to Wikipedia:

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

What this refers to is that while is a loop, which repeats a series of instructions as long as a condition is true or false.

"While this is true" and "While this is false", this will be the principle of operation of each while loop, regardless of the condition.

If, for example, we had that a while loop will be executed as long as a variable i is less than 6, this will mean that as long as i less than 6 is true, everything inside the loop will be executed. Otherwise, the loop stops and the instructions are not executed.

One way to think of this is to imagine a constantly repeating If conditional. Taking the example above, we would have the conditional asking if i < 6 as many times as necessary, executing the code, and stopping only if the condition is not met.

image.png

Enough talk, now an important question, what does a while loop look like in code?

HiveDivider.png

What do while loops look like in code?


1_8kjZYCzEQXGgVuGEuWkdPg.png

Shoutout to Elizabeth and Medium.com

In the same way that a for loop consists of a "header", where the condition is placed (next to the while) and the "body", which is the text block where the code to be executed is placed, exactly the same happens for the while loop:

while (condition):
      // Code that will be looped

With the example of i being less than 6, just change the condition to i < 6 and you have a functional while loop:

while i < 6:
    // Instructions
      i += 1

Note: In this case we use i += 1 to increase the value of i until it reaches 6, breaking the cycle. Otherwise, the cycle would run infinitely, which can cause problems.

HiveDivider.png

While Loop Statements


statements.webp

Shoutout to Real Python

The while is a relatively simple cycle, where we do not have to define a large number of parameters. However, to have full control over them, we must also know their statements, which are 3:

  • break
  • continue
  • else

Let's go through each of these:

break

The break is used when we want to end the loop at the occurrence of a particular instruction, even if the condition that makes the loop run is true. To understand this, let's look at the following line of code:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

In this case, we see that at first, because i is 1, the condition i < 6 will be fulfilled. However, a conditional is placed, which will cause that when the third value is reached, using break, the cycle is stopped prematurely.

continue

We can view continue as a skip, which whenever executed, will skip the current iteration and immediately move on to the next one. If we observe:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

In this case, because of the conditional, when i is 3, the instruction print(i) will not be executed. It will go back to the while i < 6 line and i will be incremented again, now executing print since i is now 4, not 3. Seeing the result in code, we would have:

>>>
1
2
4
5
6

else

Like else in a conditional if, here, it will execute instructions when the cycle is not being fulfilled, specifically, once it ends.

Viewing the following code:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6").

We will have the output:

1
2
3
4
5
i is no longer less than 6

Note: at the end of the cycle, else statements are only executed once. Don't expect a bunch of print("the cycle has finished") after code completion.

HiveDivider.png

A little example


image.png

For this example, we will create a list where we will store a certain amount of numbers, which we will call list_numbers:

list_numbers = ['555-444356','555-4669570575','555-467590456']

What we will do is display each number, one by one, using the while loop. For this, we will create two variables, one that will contain the number and the other that will help us to position ourselves in each index of the list to take the numbers. We will call them index and number.

index = 0
number = ''

Now, what we will do is use the len() function, which allows us to get the size of an iterable object, such as a list in this case. Our list has 3 elements, so using len(list_numbers), we'll get a value of 3. Taking this into account, we will do the following:

while index < len(list_numbers):
    number = list_numbers[index]
    print(number)
    index += 1

Here, we say that as long as the value of index is less than len(list_numbers), which is 3, the value of number will be the element of our list at the given index.

Then, we will display the value of number and increase the value of index by 1, which will cause the cycle to repeat until the condition is no longer met.

If we run our code, we will have:

>>>
555-444356
555-4669570575
555-467590456

HiveDivider.png

The simplicity of while cycles and their use in more ambiguous situations than for cycles make them ideal choices for many programmers. All you need is a condition to be met and Bam! While loop

After this article, you will be able to implement while loops in your projects and exploit their potential without any problems. Buckle Up! Soon we will talk about classes and functions.

HiveDivider.png

Thanks for your support and good luck!

HiveDivider.png

@jesalmofficial.png

HiveDivider.png

while gente_le_gusta == True:
seguir_posteando = True


WhileLoop.webp

Shoutout to and Real Python

HiveDivider.png

En este artículo encontrarás:

  • Introducción
  • ¿Qué es un ciclo while?
  • Como lucen los ciclos while en código
  • Declaraciones de bucle While
  • Un pequeño ejemplo

HiveDivider.png

En esta edición de Coding Basics, continuaremos con los ciclos. En el capítulo anterior hablamos de los ciclos for y su utilidad cuando trabajamos con objetos iterables como listas, diccionarios o incluso cadenas, donde ya conocemos el número máximo de elementos.

Sin embargo, ¿qué ocurre si sólo queremos que un bucle se ejecute mientras se cumpla una condición? Supongamos que queremos crear un programa que busque contenidos en Internet, todo ello mientras tengamos conexión a Internet. Para ello, utilizamos el bucle while.

Así que, si tienes curiosidad por saber cómo funciona el bucle while o quieres refrescar tus conocimientos, este es el lugar adecuado. Sin nada más que decir.

¡Empecemos!

HiveDivider.png

¿Qué es un ciclo while?


1200px-Do-while-loop-diagram.svg.png

Shoutout to Wikipedia.com

Según Wikipedia:

Un bucle while es una sentencia de flujo de control que permite ejecutar código repetidamente en función de una determinada condición booleana.

A lo que esto se refiere es que while es un bucle, que repite una serie de instrucciones mientras una condición sea verdadera o falsa.

"Mientras esto sea cierto" y "Mientras esto sea falso", este será el principio de funcionamiento de cada bucle while, independientemente de la condición.

Si, por ejemplo, teníamos que un bucle while se ejecutará mientras una variable i sea menor que 6, esto significará que mientras i menor que 6 sea cierto, todo lo que esté dentro del bucle se ejecutará. En caso contrario, el bucle se detiene y las instrucciones no se ejecutan.

Una forma de pensar en esto es imaginar un condicional If que se repite constantemente. Tomando el ejemplo anterior, tendríamos el condicional preguntando si i < 6 tantas veces como sea necesario, ejecutando el código, y parando sólo si la condición no se cumple.

image.png

Basta de charla, ahora una pregunta importante, ¿qué aspecto tiene un bucle while en código?

HiveDivider.png

¿Cómo se ven los bucles while en código?


1_8kjZYCzEQXGgVuGEuWkdPg.png

Shoutout to Elizabeth and Medium.com

De la misma forma que un bucle for consta de una "cabecera", donde se coloca la condición (junto al while) y el "cuerpo", que es el bloque de texto donde se coloca el código a ejecutar, exactamente lo mismo ocurre para el bucle while:

while (condición):
      // Código que se ejecutará en el bucle

Con el ejemplo de que i es menor que 6, basta con cambiar la condición por i < 6 y ya tenemos un bucle while funcional:

while i < 6:
    // Instrucciones
      i += 1

Nota: En este caso usamos i += 1 para incrementar el valor de i hasta que llegue a 6, rompiendo el ciclo. De lo contrario, el ciclo se ejecutaría infinitamente, lo que puede causar problemas.

HiveDivider.png

Declaraciones de bucle While


statements.webp

Shoutout to Real Python

El while es un ciclo relativamente sencillo, en el que no tenemos que definir un gran número de parámetros. Sin embargo, para tener un control total sobre ellos, también debemos conocer sus sentencias, que son 3:

  • break
  • continue
  • else

Repasemos cada uno de ellos:

break

El break se utiliza cuando queremos terminar el bucle en la ocurrencia de una instrucción particular, incluso si la condición que hace que el bucle se ejecute es verdadera. Para entender esto, veamos la siguiente línea de código:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

En este caso, vemos que en un principio, al ser i 1, se cumplirá la condición i < 6. Sin embargo, se coloca una condicional, que hará que cuando se alcance el tercer valor, mediante break, se detenga el ciclo antes de tiempo.

continue

Podemos ver continue como un skip, que siempre que se ejecute, saltará la iteración actual y pasará inmediatamente a la siguiente. Si observamos:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

En este caso, debido a la condicional, cuando i es 3, la instrucción print(i) no se ejecutará. Se volverá a la línea while i < 6 y se volverá a incrementar i, ejecutando ahora print ya que ahora i es 4, no 3. Viendo el resultado en código, tendríamos:

>>>
1
2
4
5
6

else

Al igual que else en un if condicional, aquí, ejecutará instrucciones cuando el ciclo no se esté cumpliendo, concretamente, una vez finalice.

Viendo el siguiente código:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i ya no es menor que 6").

Tendremos la salida:

1
2
3
4
5
i ya no es menor que 6

Nota: al final del ciclo, las sentencias else sólo se ejecutan una vez. No esperes un montón de print("el ciclo ha terminado") tras la finalización del código.

HiveDivider.png

Un pequeño ejemplo


image.png

Para este ejemplo, crearemos una lista donde almacenaremos una cierta cantidad de números, a la que llamaremos list_numbers:

list_numbers = ['555-444356','555-4669570575','555-467590456']

Lo que vamos a hacer es mostrar cada número, uno a uno, utilizando el bucle while. Para ello, crearemos dos variables, una que contendrá el número y otra que nos servirá para posicionarnos en cada índice de la lista para tomar los números. Las llamaremos index y number.

index = 0
number = ''

Ahora, lo que haremos será utilizar la función len(), que nos permite obtener el tamaño de un objeto iterable, como en este caso una lista. Nuestra lista tiene 3 elementos, por lo que usando len(lista_numeros), obtendremos un valor de 3. Teniendo esto en cuenta, haremos lo siguiente:

while index < len(list_numbers):
    number = list_numbers[index]
    print(number)
    index += 1

Aquí decimos que mientras el valor de índice sea menor que len(lista_numbers), que es 3, el valor de número será el elemento de nuestra lista en el índice dado.

Entonces, mostraremos el valor de number e incrementaremos el valor de index en 1, lo que hará que el ciclo se repita hasta que la condición deje de cumplirse.

Si ejecutamos nuestro código, tendremos:

>>>
555-444356
555-4669570575
555-467590456

HiveDivider.png

La sencillez de los ciclos while y su uso en situaciones más ambiguas que los ciclos for los convierten en la opción ideal para muchos programadores. Todo lo que se necesita es que se cumpla una condición y ¡Bam! Bucle while

Después de este artículo, serás capaz de implementar bucles while en tus proyectos y explotar su potencial sin problemas. ¡Abróchate el cinturón! Pronto hablaremos de clases y funciones.

HiveDivider.png

Gracias por su apoyo y ¡buena suerte!

HiveDivider.png

@jesalmofficial.png

Sort:  

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.