En este cuaderno, vamos a investigar:
¡Bucles! (Loops) Los bucles nos permiten repetir un pedazo de código una y otra vez, ya sea un cierto número de veces o hasta que ocurra algo.
El por
bucle (for
loop) nos permite ejecutar un pedazo de código un número determinado de veces y crea un variable para nosotros que nos dice cuántas veces se ha ejecutado:
for i in range(6):
print(i)
0 1 2 3 4 5
mientras
bucle (while
loop) nos permite ejecutar un pedazo de código hasta que suceda algo específico:n = 10
while n > 6:
print("n sigue siendo mayor que 6...")
n -= 1
print("¡n ahora es igual a 6!")
n sigue siendo mayor que 6... n sigue siendo mayor que 6... n sigue siendo mayor que 6... n sigue siendo mayor que 6... ¡n ahora es igual a 6!
mis_colores_favoritos = ["rojo", "verde", "azul", "naranja"]
print(mis_colores_favoritos)
print(mis_colores_favoritos[0])
print(mis_colores_favoritos[3])
mis_colores_favoritos += ["morado"]
print(mis_colores_favoritos)
for color in mis_colores_favoritos:
print(color)
['rojo', 'verde', 'azul', 'naranja'] rojo naranja ['rojo', 'verde', 'azul', 'naranja', 'morado'] rojo verde azul naranja morado
Echa un vistazo al código a continuación:
print("Hola")
print("Hola")
print("Hola")
print("Hola")
print("Hola")
print("Hola")
print("Hola")
print("Hola")
Este programa realiza exactamente la misma acción ocho veces. Aburrido, ¿verdad? Podemos escribirlo de una manera menos tediosa usando un bucle.
Con un bucle, podemos pedirle a la computadora que ejecute parte de nuestro código un cierto número de veces antes de continuar. El código que queremos ejecutar repetidamente se llama el "cuerpo" del bucle.
El siguiente programa utiliza un bucle. Ejecútelo y observe cómo tiene el mismo resultado que el anterior.
for i in range(8):
print("Hola")
Éste es un ejemplo de por
bucle (for
loop).
Ejecuta un bloque de código, print("Hola")
, ocho veces.
Como una declaración if
(si
), el bucle for
(por
) tiene un cuerpo. El cuerpo se compone de todo el código sangrado que sigue a la línea que comienza con for
. La computadora ejecutará todas las declaraciones en el cuerpo tantas veces como diga el bucle; en este caso, 8.
¡Puedes tener más de una declaración en el cuerpo! ¿Qué crees que imprimirá el siguiente programa?
for i in range(4):
print("Hola")
print("Mundo")
La computadora ejecuta todo el código en el cuerpo del bucle, luego vuelve al principio y lo ejecuta todo de nuevo, tantas veces como le pidamos. Por eso se llama "bucle": la computadora recorre el cuerpo uno por uno, llega al final, luego da vueltas hasta el principio, hasta que lo ha hecho tantas veces como sea necesario.
Echa un vistazo a este programa. ¿Qué crees que imprime?
for i in range(4):
print("Hola")
print("Mundo")
print("!")
Ten en cuenta que el signo de exclamación en el programa anterior se imprime una vez, solo después de que la computadora haya terminado con el ciclo. El signo de exclamación no forma parte del cuerpo del bucle. Cuando la computadora termina con el ciclo, pasa al resto de las declaraciones.
Eche un vistazo al bucle a continuación: ¿qué imprime?
for i in range(8):
print("Imprimeme ocho veces")
print("¡También imprímame ocho veces!")
Creando un for loop también crea una variable que nos dice qué tan lejos está la computadora en el ciclo. Podemos llamar a esta variable el contador de bucle.
¿Notaste la i
en los bucles que hemos escrito hasta ahora? Este es el nombre del contador. ¡Podemos usar el contador como cualquier otra variable!
¿Qué crees que imprimirá el siguiente código?
for i in range(8):
print(i)
0 1 2 3 4 5 6 7
¡Esto podría no haber sido lo que esperabas!
La primera vez que se ejecuta el bucle, el contador tiene el valor 0.
La segunda vez que se ejecuta el bucle, el contador tiene el valor 1.
La tercera vez, tiene el valor 2.
... y así sucesivamente, hasta que el ciclo termine.
Esto significa, como viste anteriormente, que un bucle que se ejecuta ocho veces tendrá un contador que comienza en cero y termina en siete. ¡Esto podría ser sorprendente! Es un ejemplo de por qué decimos que a las computadoras les gusta comenzar a contar desde cero en lugar de desde uno.
El siguiente código es un ligero ajuste al bucle anterior. ¿Puedes adivinar lo que imprime?
for i in range(4):
print(i * 2)
La multiplicación funciona, ya que podemos tratar el contador de bucles como cualquier variable normal.
0
3
6
9
El cuerpo del bucle no tiene que estar compuesto simplemente de sentencias de print
; los bucles pueden ejecutar cualquier código, ¡incluso sentencias if
o otros bucles!
Eche un vistazo al siguiente bucle. Aquí, combinamos un if
y un bucle juntos. ¿Puedes adivinar lo que imprime?
for i in range(8):
if i == 4:
print("My greetings.")
My greetings.
Repasemos esto juntos.
Primero, usamos for i in range(8)
para crear un ciclo que se ejecuta ocho veces. El cuerpo del bucle es cada declaración sangrada después de esto, por lo que el cuerpo es este código:
if i == 4:
print("My greetings.")
¡El cuerpo tiene una declaración if
! Y además de eso, el if
también tiene un cuerpo: una sola declaración de print
. Solo imprimiremos la frase "Mis saludos". si i
pasa a tener el valor 4.
La computadora verificará esta declaración if
ocho veces. La primera vez, i
tendrá el valor 0. La segunda vez, tendrá el valor 1. Luego 2, luego 3, luego 4, luego 5, luego 6, finalmente 7. ¿Cuántas veces i
tiene el valor 4? ¡Sólo una vez! Entonces la impresión solo ocurre una vez.
El siguiente bucle utiliza un concepto similar. ¿Qué crees que imprime?
for i in range(6):
if i != 2:
print(i)
Aquí imprimimos todos los números del 0 al 5 ¡excepto el 2!
Cuando hayas terminado con eso, eche un vistazo al siguiente código:
mi_numero = 5
for i in range(3):
mi_numero += 1
print(mi_numero)
Ejecute este código y mira lo que genera. ¿Que esta pasando aqui?
Recuerda que los cuerpos de los bucles pueden ejecutar cualquier código. Incluso podemos cambiar variables en el cuerpo de un bucle.
Aquí, creamos una variable, luego le agregamos 1 en un ciclo. Ese bucle se ejecuta 3 veces. Después del primer ciclo, mi_numero
será 6, luego será 7, luego será 8, luego el ciclo terminará.
Efectivamente, esto suma 3 a la variable, ¡así que terminamos imprimiendo 5 + 3 = 8!
¡Antes de continuar, asegúrese de comprender los bucles for
lo suficientemente bien como para escribir algunos por su cuenta!
If you get stuck, look at the examples above. You may find it helpful to copy and paste some previous code. Of course, always feel free to ask the instructors for help.
Can you:
# Write your code here
If you were able to do one or more of these, show it off to the instructors!
while
¶There are actually two kinds of loops in Python!
We have looked at the for
loop, where we can specify exactly how many times we want our loop to go for.
Now let's look at the while
loop. With these loops, rather than saying how many times we want the loop to go for, we say that the loop should go until something happens.
The following code is an example of a while
loop:
n = 1
while n < 4:
print("Hello!")
n = n + 1
This loop is a quite a bit more complicated!
Like a for
loop, a while
loop has a body, but it also has a condition.
In a while
loop, we do not specify how many times the body should run - instead, we say that the loop should continue running until its condition becomes false.
In the above loop, the condition is n < 4
. This is a question that is either true or false; is n
less than 4?
The computer asks this question at the start of each loop. If the answer to the question is no - if it is false - the loop will stop! If the answer is yes, it will keep going. It is a lot like an if
statement that repeats by returning to the beginning when it is done.
Let's see another example:
n = 3
while n < 5:
print(n)
n = n + 1
Run this program and notice what it prints. It ends up just printing 3 and 4. Let's step through the loop together and see why this is:
First, the program sets the value of the variable n
to 3.
Then, it encounters the while
loop. Before running the body, it checks the loop's condition. Is n
less than 5? Yes! So, the loop body is run.
In the loop body, we first print the value of n
. This is 3, so the number 3 gets printed. Then, we increase the value of n
by 1. n
now holds the value 4.
Now that the body is done, the loop wants to run it again. So it checks the condition. Is n
less than 5? Yes, it stil is! So we run the body again. The number 4 is printed, and n
increases to 5.
The loop wants to run again, so it checks the condition again. Is n
less than 5? Oh - no, not anymore. So now the loop stops, and it is done!
Take a look at the following code. What do you think will happen?
n = 0
while n < 5:
print(n)
What is the condition of this loop? It is n < 5
. So, the loop will only stop when n
is not less than 5. But n
is always 0! We do not change the value of n
in the loop, so the loop never stops!
This is often known as an infinite loop, for obvious reasons. Generally, an infinite loop is not a good thing. They usually result from making a mistake in a while
loop - most often, from forgetting to change a variable in the loop.
You can stop an infinite loop by clicking on the program's play button again.
Before you move on, test your knowledge of the while
loop.
Try your best at these challenges - you can refer to anything else in the notebook or ask for an instructor's help.
Can you:
while
loop that prints something 16 times?while
loop that shows every number from 0 to 8, including 8?while
loop that shows every even number from 0 to 8, including 8?# Write your code here
Again, if you were able to do one or more of these, show it off to the instructors!
So far, we have seen variables that store exactly one thing: a single number, a single word, etc. However, variables can store more than one thing if we use lists!
my_friends = ["Sean", "Matt", "Hayden"]
print(my_friends)
The my_friends
variable is an example of a list! It stores 3 values instead of just one. We can create a list by writing multiple things down, then separating them with commas and surrounding all of them with square brackets.
When we print my_friends
, you'll notice it prints out everything in the list.
What if we want just the first friend? Or just the second one?
Each thing in a list has an index. This is a number describing where that thing is in the list - is it in the first position? The fourth?
The first item in a list always has index 0.
The second will have index 1.
The third will have index 2.
And so on.
Just like with a for
loop counter, the computer has started counting at 0! This can be very confusing, since the first item is NOT at index 1, but at index 0.
fruits = ["Banana", "Strawberry", "Lemon", "Mango"]
print(fruits[0])
This program shows how we can use an index to access the items in an array. Run it, and notice how just the first fruit in the list, Banana, is printed.
We can use this pattern with any list: if we have a variable that contains a list, typing the name of the variable will give back the entire list, but typing the name of the variable and a set of square brackets with a number inside will give back a single item in the list with the appropriate index.
Here are some more examples:
print(fruits[1])
print(fruits[2])
print(fruits[3])
print(fruits[2], fruits[3], fruits[0])
You can use the same technique to modify elements in the list:
fruits[3] = "Blueberry"
print(fruits)
This has changed the item at index 3 - the fourth item - into "Blueberry". It was "Mango".
We can also add entirely new items to a list, in a similar way to adding to numbers or words. The following program adds two new fruits to our list:
fruits += ["Lime"]
fruits += ["Blackberry"]
After adding these items, the fruits
list has 6 fruits in it. What happens when we try to access the element at index 6? This would be the seventh item, but as we know, there are only six of them...
print(fruits[6])
An error, of course! So be careful when directly accessing items in a list like this - if you give an incorrect index, the program will crash.
Be careful also when adding new items to a list. The square brackets around the item you want to add are required! The following program might look okay, but watch out, it is missing the square brackets around the 3:
numbers = [0, 1, 2]
numbers += 3
print(numbers)
numbers
array?Take a look at the two programs below. The first creates a list, and the second prints it out.
prime_numbers = [2, 3, 5, 7, 9, 11]
print(prime_numbers)
[2, 3, 5, 7, 9, 11]
Without touching the first program, can you:
As you have seen, the form of a for
loop is:
for i in range(10)
...of course, we can put any number in place of the 10.
So why have we been using the word range
? Well, roughly, range(10)
is actually a list of all of the numbers from 0 to 9!
How can we tell? Take a look at the following program:
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(i)
Notice that this does the exact same thing as the normal range
based for
loop!
for i in range(10):
print(i)
We can actually make the loop counter do whatever we want by replacing range
with any list! The loop counter variable will be given the value of each item in the list, in the order they are in the list.
For example: I can print every even number from 0 to 6 like this:
for i in [0, 2, 4, 6]:
print(i)
I can print every number from 0 to 6 backwards like this:
for i in [6, 5, 4, 3, 2, 1, 0]:
print(i)
I can print a bunch of totally random numbers:
for i in [26, 197420, -5]:
print(i)
I can even use the counter for words!
for i in ["Hello", "my", "friend!"]:
print(i)
Be careful about the formatting: there must be commas between each of the items! Notice that this program produces an error, because it is missing commas:
for i in [1 2 3 4]:
print(i)
for
loop? Can you print both words and numbers in the same loop?range
?for i in range(3):
print(i)
0 1 2
Whew! This is the end of day 3. Give yourself another pat on the back (literally, if you want.)
See if you can use what you've learned to complete a few of these challenges. You can look back at anything in the notebook and, of course, ask any of the instructors for help.
Can you write a program below that prints out every number from 0 to 10, including 10?
# Write your code here
(When you are done, your program should produce this):
0
1
2
3
4
5
6
7
8
9
Can you write a program below that prints out every even number from 10 to 20, including 20?
# Write your code here
(When you are done, your program should produce this):
10
12
14
16
18
20
The following program has a loop that prints every number in the numbers
list. Can you make this loop instead change every number in the list to 0?
numbers = [1, 2, 3, 4]
print(numbers)
for i in range(4):
print(numbers[i])
print(numbers)
[1, 2, 3, 4] 1 2 3 4 [1, 2, 3, 4]
(When you are done, your program should produce this):
[1, 2, 3, 4]
[0, 0, 0, 0]
By only changing the following loop, can you set numbers_contains_six
to True
if the numbers
list contains the number 6?
numbers = [1, 2, 3, 4, 5, 6]
numbers_contains_six = False
for i in numbers:
print(i)
print(numbers_contains_six)
1 2 3 4 5 6 False
(When you are done, your program should produce this):
[1, 2, 3, 4, 5, 6]
True
The program below has a really long list of numbers. To show you how big it is, it also prints the length of the list, which is how many elements it has. You can get the length of any list by using the len
command - look at the program below to see how it is used.
Can you extend this program to print the first and last elements of this list (without looking up what they are)?
very_long_list = [3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8, 1, 14, 7, 0, 13, 6, 19, 12, 5, 18, 11, 4, 17, 10, 3, 16, 9, 2, 15, 8]
print(very_long_list)
print(len(very_long_list))
Lists can contain other lists. These are sometimes called multi-dimensional lists.
Take a look at the following program. The list_of_lists
list contains 3 items, and each one of those items is a list itself! So, when we access the first element by using, say list_of_lists[0]
, the resulting item is also a list.
list_of_lists = [[1, 1], [2, 3, 5], [8, 13]]
print(list_of_lists)
print(list_of_lists[0])
print(list_of_lists[1])
print(list_of_lists[2])
Knowing this, can you extend the program to also print the last element of each of the 3 lists inside of list_of_lists
?
If you managed to complete some or all of these, give yourself a pat on the back and show the instructors your awesome work!