for upvote in post:
print("thanks")
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.
Let's get started!
What is a For Loop?
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?
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
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
Thanks for your support and good luck!
for upvote in post:
print("gracias")
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.
隆Comencemos!
驴Qu茅 es un ciclo for?
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?
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
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
Gracias por tu apoyo y 隆Buena suerte!