for upvote in post:
print("thanks")
Shoutout to Real Python
In this article you'll find:
- Introduction
- What is a for loop?
- What does a for loop look like in code?
- A little example
Good morning, afternoon and evening to all programming fans. Yesterday I wrote about one of the pillars of programming: Conditional statements. Now, it's time to take it a step further.
Today, we will talk about for loops, which will allow us to execute a lot of instructions until a limit is reached.
- Do you want to see all the items in a long list? Use a For loop
- Do you want to add all the numbers from 1 to 100 together? For Loop
- Do you want to place all the new entries on your web page when it refreshes? For Loop
Enough Talk.
What is a For Loop?
Shoutout to GeeksforGeeks
If we go with the technical definition of a for cycle, we will have:
a for-loop or for loop is a control flow statement for specifying iteration.
However, this can be simplified, knowing that a for-loop is a control structure that allows us to execute the same instructions as many times as we specify.
I know it may still sound confusing, however, an example illustrates it much better.
You are going through your office payroll document and you have to pass each employee's information to an excel sheet. If you were to do it manually, you would have to type this data one by one, which would probably take you hours.
or
You can design a program that goes through each row of the list and saves the information in the new document, all in seconds. You just specify the number of employees and tell it to take their information. Then, when it reaches the number limit, it will stop.
The program that will do this is the for loop, which will take, for example, the 4 employees from the employee list and pass them one by one to the new document.
Now we know what the for loop does, but what does a for loop look like in code?
What does a for loop look like in code?
Shoutout to Treehouse Blog
Taking as a reference a programming language with a simple to understand syntax such as Python, a for loop is commonly written as:
for number in list:
[Instructions]
or
for number in range(num1,num2, inc):
[Instructions]
In the first form, what we do in principle is to take an iterable element (such as a list, a tuple, a dictionary or even a string), and increase the index of "number" one by one to go through each of its positions. This part of the cycle is known as the header, where we define the number of iterations.
Note: Don't worry about the name where It says "number", this is just a variable to store the indexes of the iterations temporally. You can name It index, thing, dog... Whatever you want.
Then, the instructions that are executed repeatedly in the cycle will be known as the body of the for loop.
For the second way, when we do not have a particular object to iterate or we want to create a large number of elements quickly, we use the range function, where, according to its structure:
range(num1,num2, inc)
- num1 is the value from which it starts counting. Ex: If we put the number 2, then it will start counting from this value.
- num2, is the number where it stops counting. If we put 100, range will stop counting at this value.
- inc is the increment, which can be positive or negative. If we put 2, then range will count with increments of 2. Similarly, if we put negative numbers, it will start counting backward, from num2 to num1.
So, if for example we have the following for loop
for number in range(0,10,2):
This will be the equivalent to go through each element of a list that goes from 0 to 10, jumping two numbers:
list = [0,2,4,6,8,10]
for number in list:
Note: Range has default values for num1 and inc. This means that by default, If you don't write any beginning number, It'll automatically start at 0, same for inc, where the default increment is 1.
A little example
Shoutout to Net solutions
We have a list of programming languages we know, and a company asks us to pass on the names of these languages in the form of another list. How do we do this?
programming_languages = ['Python','C#','Javascript','Assembler']]
list_for_company = []
Using the for loop. Simply, we will define that for each element of the programming_languages list, we will pass these elements to the other list:
for language in programming_languages:
list_for_company.append(language)
Note: The append function is used to add new elements to a list. In case of only placing list_for_company = language, we will have that it will always be refreshed and it will only record "Assembler" at the end.
Now, if we show the second list with:
print(list_for_company)
We'll have:
>>>['Python', 'C#', 'Javascript', 'Assembler']
Which confirms that our for loop has been succesful
The for loops are the most used loops in programming, because they allow us to establish limits and work with variables in a direct way. However, there are occasions where the value of an iterable object is not known in advance or we only want it to be executed as long as a condition is met.
For this, other cycles are used such as while, do while and until cycles. However, this will be the subject of another article. For now, this is what you need to know about using loops.
If you want to know the particular syntax of a for loop in your programming language, check out this very useful article, written by Rattanak Chea at Dev.to
for upvote in post:
print("gracias")
Shoutout to Real Python
En este artículo encontrarás:
- Introducción
- ¿Qué es un ciclo for?
- ¿Como luce un ciclo for en código?
- Un pequeño ejemplo
Buenos días, tardes y noches a todos los aficionados a la programación. Ayer escribí sobre uno de los pilares para la programación: Las sentencias condicionales. Ahora, es el momento de ir un paso más allá.
Hoy hablaremos de los bucles for, que nos permitirán ejecutar un montón de instrucciones hasta llegar a un límite.
- ¿Quieres ver todos los elementos de una lista larga? Utiliza un bucle For
- ¿Quieres sumar todos los números del 1 al 100? Bucle For
- ¿Quieres colocar todas las nuevas entradas en tu página web cuando se actualice? Bucle For
Basta de charla.
¿Qué es un ciclo for?
Shoutout to GeeksforGeeks
Si vamos con la definición técnica de un ciclo for, tendremos:
un bucle for o bucle for es una sentencia de flujo de control para especificar la iteración.
Sin embargo, esto se puede simplificar, sabiendo que un bucle for es una estructura de control que nos permite ejecutar las mismas instrucciones tantas veces como especifiquemos.
Sé que aún puede sonar confuso, sin embargo, un ejemplo lo ilustra mucho mejor.
Estás revisando el documento de nóminas de tu oficina y tienes que pasar la información de cada empleado a una hoja excel. Si lo hicieras manualmente, tendrías que teclear estos datos uno a uno, lo que probablemente te llevaría horas.
o
Puedes diseñar un programa que recorra cada fila de la lista y guarde la información en el nuevo documento, todo en segundos. Sólo tienes que especificar el número de empleados y decirle que tome su información. Entonces, cuando llegue al límite de número, se detendrá.
El programa que hará esto es el bucle for, que tomará, por ejemplo, los 4 empleados de la lista de empleados y los pasará uno a uno al nuevo documento.
Ahora ya sabemos lo que hace el bucle for, pero ¿qué aspecto tiene un bucle for en código?
¿Como luce un ciclo for en código?
Shoutout to Treehouse Blog
Tomando como referencia un lenguaje de programación con una sintaxis sencilla de entender como Python, un bucle for se escribe comúnmente como:
for number in list:
[Instructions]
or
for number in range(num1,num2, inc):
[Instructions]
En la primera forma, lo que hacemos en principio es tomar un elemento iterable (como una lista, una tupla, un diccionario o incluso una cadena), e incrementar el índice de "número" de uno en uno para recorrer cada una de sus posiciones. Esta parte del ciclo se conoce como cabecera, donde definimos el número de iteraciones.
Nota: No te preocupes por el nombre donde pone "número", esto es sólo una variable para almacenar los índices de las iteraciones temporalmente. Puedes llamarla índice, cosa, perro... Lo que quieras.
Entonces, las instrucciones que se ejecutan repetidamente en el ciclo se conocerán como el cuerpo del bucle for.
Para la segunda forma, cuando no tenemos un objeto en particular para iterar o queremos crear un gran número de elementos rápidamente, utilizamos la función rango, donde, de acuerdo a su estructura:
range(num1,num2, inc)
- num1 es el valor a partir del cual empieza a contar. Ej: Si ponemos el número 2, entonces empezará a contar a partir de este valor.
- num2, es el número donde deja de contar. Si ponemos 100, el rango dejará de contar en este valor.
- inc es el incremento, que puede ser positivo o negativo. Si ponemos 2, entonces range contará con incrementos de 2. Del mismo modo, si ponemos números negativos, empezará a contar hacia atrás, desde num2 hasta num1.
Así, si por ejemplo tenemos el siguiente bucle for
for number in range(0,10,2):
Esto equivaldrá a recorrer cada elemento de una lista que va de 0 a 10, saltando dos números:
list = [0,2,4,6,8,10]
for number in list:
Nota: Range tiene valores por defecto para num1 e inc. Esto significa que, por defecto, si no escribe ningún número de inicio, se iniciará automáticamente en 0, lo mismo para inc, donde el incremento por defecto es 1.
Un pequeño ejemplo
Shoutout to Net solutions
Tenemos una lista de lenguajes de programación que conocemos y una empresa nos pide que le pasemos los nombres de esos lenguajes en forma de otra lista. ¿Cómo lo hacemos?
programming_languages = ['Python','C#','Javascript','Assembler']]
list_for_company = []
Utilizando el bucle for. Simplemente, definiremos que por cada elemento de la lista lenguajes_programación, pasaremos estos elementos a la otra lista:
for language in programming_languages:
list_for_company.append(language)
Nota: La función append se utiliza para añadir nuevos elementos a una lista. En caso de sólo colocar lista_para_empresa = idioma, tendremos que siempre se refrescará y sólo registrará "Ensamblador" al final.
Ahora, si mostramos la segunda lista con:
print(list_for_company)
We'll have:
>>>['Python', 'C#', 'Javascript', 'Assembler']
Lo que confirma que nuestro bucle for ha tenido éxito
Los bucles for son los más utilizados en programación, ya que nos permiten establecer límites y trabajar con variables de forma directa. Sin embargo, hay ocasiones en las que no se conoce de antemano el valor de un objeto iterable o sólo queremos que se ejecute mientras se cumpla una condición.
Para ello se utilizan otros ciclos como while, do while y until. Sin embargo, esto será tema de otro artículo. Por ahora, esto es lo que necesitas saber sobre el uso de bucles.
Si quieres conocer la sintaxis particular de un bucle for en tu lenguaje de programación, consulta este artículo muy útil, escrito por Rattanak Chea en Dev.to