This lesson is for complete beginners. You can follow the instructions with the turtle board game, a coin, and paper. No programming experience is needed. Start with the order of instructions, then add one new idea at a time.
The execution links below open a step-by-step debugger. Use Next and Previous to watch the current instruction, variables, and board or text output. The execution page keeps your selected language.
0. Following instructions in order
A program is a set of instructions. The computer follows them in a specified order, usually from top to bottom unless a condition, loop, or function changes the flow. The order matters: the computer does not rearrange your instructions to match what you meant.
Playing TLAC: use a small coin to mark the current instruction. Blue numbers such as 0001 tell you where you are. Yellow cards contain instructions; green cards contain comments for the reader.
A morning routine, in order
0001
Function call: Brush my teeth
0002
Function call: Comb my hair
0003
Function call: Go to work
This order means brushing your teeth, combing your hair, and then going to work. Now compare it with the same actions in a different order:
The same actions, a different result
0001
Function call: Brush my teeth
0002
Function call: Go to work
0003
Function call: Comb my hair
Here you leave for work before combing your hair. All three instructions are still present, but the sequence changes the result. This is why checking the order is one of the first steps in finding a programming mistake.
The original lesson also refers to this Richard Feynman lecture when discussing how literally computers follow instructions.
1. Variables
A variable is a name for a stored value. Think of a labeled box: the name tells you which box to use, and its current contents are the value. A variable can hold a number such as 5 or text such as “hello”. Text is called a string.
Names such as x or last_name are easy to use. In the examples, names do not contain spaces: last_name is one name, while “last name” is a phrase. Strings are shown in quotation marks to distinguish them from names and numbers. For example, last_name can store “Einstein”.
The kind of value matters. An identification number such as 123456789 can be written as a number, but “123-45-6789” is text because it includes separators. Choose a representation that preserves the information you need, including leading zeros when they matter.
A variable’s value can change. Setting x to 3 and later setting x to 5 replaces the old value; x now holds 5. This operation is called assignment. It records a value at a particular point in the program, rather than declaring a mathematical equation that must always be true.
Playing TLAC: write each variable’s name and current value on a separate sheet. Cross out the old value whenever an assignment changes it.
2. Statements and assignment
A statement is an instruction that performs a step of the program. Assignments, function calls, and conditions are examples. Follow these three assignments in order:
Change the value of x
0001
Set x to 3
0002
Set x to 5
0003
Set x to its current value + 1
Line 0001 sets x to 3.
Line 0002 replaces that value with 5.
Line 0003 reads the current x (5), adds 1, and stores 6 back in x.
In the notation x = x + 1, first calculate the expression on the right using the old value. Then put the result in the variable on the left. That destination is sometimes called the lvalue. The final value is 6; the instruction does not mean that a number is mathematically equal to itself plus one.
3. Conditions and blocks
A condition asks a question with a true or false answer. A block is a group of instructions that belongs together. If a condition is true, follow its block; if it is false, skip that block. The colored enclosure and indentation show which instructions belong to it.
Initial board: X=4, Y=9, facing up
Coordinates start at 0. X counts columns from the left and Y counts rows from the top. X=4 is the fifth column. “Move forward” moves the turtle one square in the direction of its head unless another distance is given.
Choose which blocks to execute
0001
Green cards like these are comments
0002
Comments do not change what the program does
0003
Read them to understand the instructions
0004
If X is greater than 3, then
0005
X is greater than 3, so
0006
this group of instructions, inside the
0007
colored block, will run
0008
Function call: Move Turtle Forward 1 space
0009
If X is less than 3, then
0010
X is not less than 3 here, so
0011
this block will be skipped
0012
Function call: Move Turtle Forward 1 space
0013
Set X to 2
0014
This assignment moves
0015
the turtle to X=2, two squares
0016
from the left edge (the third column)
0017
If X is less than 3, then
0018
After changing X,
0019
X is less than 3, so this block
0020
will run
0021
Function call: Move Turtle Forward 1 space
Lines 0001–0003 are comments; they explain the program without moving anything. At line 0004, X is 4, so “X is greater than 3” is true. Enter the block and execute the forward move on line 0008. X stays 4; moving up changes Y from 9 to 8.
After line 0008: X=4, Y=8
At line 0009, X is still 4, so “X is less than 3” is false. Skip the block, including the move on line 0012. Line 0013 then sets X to 2: move the turtle sideways to the third column without changing Y or its direction.
After line 0013: X=2, Y=8
Line 0017 asks the same question again, but now X is 2. This time “X is less than 3” is true, so execute line 0021. The turtle moves up one square to X=2, Y=7. A condition uses the values at the moment it is checked.
Final board: X=2, Y=7
4. Procedures and functions
A function definition gives a name to a reusable group of instructions. A function call asks the program to perform that group. Defining a function does not run its body. We already used calls in the morning routine:
Calling named actions
0001
Function call: Brush my teeth
0002
Function call: Comb my hair
0003
Function call: Go to work
Now define a new turtle action: lay four eggs in a square. “Place an egg” marks the square under the turtle. “Turn right” rotates it 90° clockwise without moving to another square. These are built-in TLAC actions; the square-making function below is a new action defined by the programmer.
Define one egg pattern; use it three times
0001
Functions example
0002
Define a reusable group of instructions:
0003
Function definition: Lay four eggs in a square
0004
Function call: Place an egg under the turtle
0005
Function call: Move Turtle Forward 1 space
0006
Function call: Place an egg under the turtle
0007
Function call: Turn Turtle Right
0008
Function call: Move Turtle Forward 1 space
0009
Function call: Place an egg under the turtle
0010
Function call: Turn Turtle Right
0011
Function call: Move Turtle Forward 1 space
0012
Function call: Place an egg under the turtle
0013
The next two turns
0014
make the turtle finish
0015
facing up
0016
Function call: Turn Turtle Right
0017
Function call: Turn Turtle Right
0018
Set X to 0
0019
Display: board after changing X
0020
Display the board
0021
Function call: Lay four eggs in a square
0022
Set X to 5
0023
Display: board after changing X
0024
Display the board
0025
Function call: Lay four eggs in a square
0026
Set X to 8
0027
Display: board after changing X
0028
Display the board
0029
Function call: Lay four eggs in a square
Lines 0003–0017 define the function. Start the main instructions at line 0018: set X to 0, show the board, and call the new function on line 0021. Follow its body, then continue after the call. Next set X to 5 and call it again at line 0025. Finally set X to 8 and call it at line 0029.
Each call lays four eggs in a 2 × 2 square and finishes facing up. The three calls make three squares: twelve marked cells altogether. Instead of copying the same instructions three times, we write the pattern once and reuse it. That makes the program shorter and easier to read or change.
A function name follows the same naming idea as a variable name. Some functions also accept parameters: values used for that call. “Move forward 5 squares” gives the movement function a distance of 5. A different call can give it another distance without redefining the movement instructions.
The display instructions in this example label and show the board after changing X. They help you see what happened; they do not lay eggs or turn the turtle. Changing X moves the turtle directly, whereas the forward instruction moves it in the direction of its head.
Returning from a function: when the function finishes, continue at the instruction after the call. A return instruction can finish the function early and can also send back a result. This example reaches the end of its body without an explicit return. A function used mainly for an action, rather than a returned value, is sometimes called a procedure.
5. Input and output
Output: show what happened
Output is information or a visible result produced by a program. In TLAC, it may be a changed board or something written on paper. Here is a very small program:
Move forward five squares
0001
A very small program
0002
Function call: Move forward 5 squares
Before: X=4, Y=9
After: X=4, Y=4
The turtle starts facing up. A distance of 5 moves it from Y=9 to Y=4 while X stays 4. The changed board is the output. A printed message can also report the movement and its move number.
Input: receive information from a player
Input is information received by the program. In TLAC, a player can provide input by moving a piece when asked. The program can read the resulting position and remember it.
Remember a player’s chosen position
0001
User input example
0002
0003
Set the starting position
0004
Move the turtle directly to X=4, Y=9
0005
Ask the player: put the turtle in the top-left corner
0006
Example player response: move to X=0, Y=0
0007
Save the turtle’s X in savedX
0008
Save the turtle’s Y in savedY
0009
Ask the player: put the turtle in the bottom-right corner
0010
Example player response: move to X=9, Y=9
0011
Move the turtle directly to savedX, savedY
Line 0004 sets the usual starting position to X=4, Y=9. Blank line 0002 does nothing.
Line 0005 asks the player to move to the top-left corner. Line 0006 records an example response: X=0, Y=0.
Lines 0007 and 0008 save the current X and Y in savedX and savedY. These are copies of the values at this moment.
Lines 0009 and 0010 ask for and demonstrate a move to the bottom-right corner, X=9, Y=9.
Line 0011 returns the turtle to savedX, savedY. In this example it returns to X=0, Y=0.
The example-response instructions let the saved execution demonstrate the player’s actions. When playing on paper, the person performs those actions. A player may choose another position or make a mistake: the program remembers the position it actually reads, not the position you hoped they would choose. This makes input useful for games where one person acts as the computer and another controls the pieces.
A loop repeats a block of instructions. Instead of writing similar commands many times, describe which values to use or when to stop. Always ask: what repeats, what changes, and when does the repetition finish?
Count upward with a for loop
Use each number from 5 through 9
0001
Count from 5 through 9, including both ends
0002
For each i in 5, 6, 7, 8, 9, repeat
0003
Move the turtle directly to X=i, Y=i
0004
0005
Write: “Counted from 5 to 9”
At line 0002, i takes the values 5, 6, 7, 8, and 9. For each value, line 0003 uses i for both coordinates. The turtle visits (5,5), (6,6), (7,7), (8,8), and (9,9), making a diagonal path. Both 5 and 9 are included; 10 is not. The message on line 0005 is outside the loop, so it is written once after the loop finishes.
A countdown is useful for a rocket launch or any job whose remaining count gets smaller. Here the count controls how far the turtle moves each time.
Move 3, then 2, then 1, then 0 squares
0001
Count down from 3 through 0
0002
For each i in 3, 2, 1, 0, repeat
0003
Function call: Move forward i squares
The counter starts at 3 and decreases by 1 each time, including the final value 0. The movements are 3 + 2 + 1 + 0 = 6 squares altogether. Moving zero squares leaves the turtle in place. From X=4, Y=9 facing up, it ends at X=4, Y=3.
Sometimes the body must run at least once before checking whether to continue. This example repeats, increases a counter, and leaves the loop when the counter passes a limit. It has the behavior of a do-while loop: perform the body first, then decide whether to repeat.
Stop after the counter passes its limit
0001
Repeat first, then check whether to stop
0002
Set n1 to 1
0003
Set n2 to 3
0004
Set step to 1
0005
0006
The body will run at least once
0007
Repeat until an instruction stops this loop
0008
Write: “The value of n1 is” followed by n1
0009
1. Run the repeated action
0010
Function call: Move forward n1 squares
0011
0012
2. Increase the counter by step
0013
Add step to n1 and save the result in n1
0014
0015
3. Check whether n1 has passed n2
0016
If n1 is greater than n2, leave the loop
0017
If n1 is greater than n2, then
0018
Leave the innermost loop
0019
Write: “n1 has passed the limit”
The starting values are n1=1, n2=3, and step=1. Each pass writes n1, moves forward n1 squares, and adds step to n1. The movement distances are therefore 1, 2, and 3. After the third pass n1 becomes 4, so “n1 is greater than n2” is true and the loop exits. The final message is outside the loop.
Notice that the counter increases here. The condition is a stopping test: leave when n1 is greater than n2, otherwise repeat. Without a change that eventually makes the stopping test true, the loop could continue forever.
A loop can contain another loop. The outer loop chooses a row; the inner loop works through every item in that row. Here i and j each take the values 1, 2, and 3.
Make a 3 × 3 multiplication table
0001
For each i in 1, 2, 3, repeat
0002
Start with empty output text
0003
0004
The inner loop changes the second number
0005
For each j in 1, 2, 3, repeat
0006
Add each multiplication to the output row
0007
Add “i × j = their product” to output, with spaces
0008
0009
Display the completed row
0010
Display the text in output
0011
0012
Separate the rows with blank lines
0013
Display blank lines
For i=1, the inner loop runs with j=1, j=2, and j=3 before i changes. Then the same three j values are used for i=2 and again for i=3. There are 3 × 3 = 9 multiplications. Start a fresh output string for each row, append the three equations, and display the completed row.
Function definition: Make one pyramid row — inputs: ch, times, triangle_width
0005
Start with empty output text
0006
0007
1. First inner loop: add spaces
0008
Include the final count in this repetition
0009
Set repeat_end to triangle_width − times
0010
Repeat for counts 0 through repeat_end
0011
Add one space to output
0012
0013
2. Second inner loop: add stars
0014
Set repeat_end2 to times × 2 − 2
0015
Repeat for counts 0 through repeat_end2
0016
Add character ch to output
0017
0018
Display the text in output
0019
0020
3. Outer loop: make rows 1 through 5
0021
Use the row numbers 1, 2, 3, 4, 5
0022
For each i in 1, 2, 3, 4, 5, repeat
0023
Make one pyramid row — ch: *, times: i, triangle_width: 5
The outer loop calls the row-making function five times. It passes the star character as ch, the row number as times, and 5 as triangle_width. Inside the function, the first inner loop adds spaces, and the second adds stars. These two inner loops happen one after the other. The completed row is then displayed.
Row
Spaces
Stars
1
5
1
2
4
3
3
3
5
4
2
7
5
1
9
*
***
*****
*******
*********
In the board game, displaying text means writing the characters on paper, keeping the spaces so that the shape lines up. This program combines functions, parameters, counting, and multiple loops.
A list stores several values in order. Each value is an item or element. An index tells you an item’s position. In these examples, counting begins at 0: the first item has index 0, the second has index 1, and so on. Arrays are another way to organize indexed values; here we use lists.
For each item: follow a list of turtle commands
A for-each loop visits each item of a list in order. The list below describes a turtle route. Take one command, decide what it means, perform the action, and then take the next command. The list itself becomes data that describes a small program.
The list on line 0002 has eight commands: forward, forward, right, forward, forward, left, forward, forward. The loop begins on line 0005. The conditions choose the matching turtle action for the current command. From X=4, Y=9 facing up, two forward moves reach (4,7); turning right and moving twice reaches (6,7); turning left and moving twice reaches (6,5), facing up.
Now use a list of fruit names. We keep the stored words in English so that the alphabetical order and the saved output agree in all three versions of this lesson. The initial list contains banana, apple, peach, and pear.
Index
Stored value
0
banana
1
apple
2
peach
3
pear
The notation fruits[0] means the item at index 0: banana in the initial list. fruits[3] means the fourth item: pear. An index identifies a position, so the word at that position may change when the list is rearranged.
Reverse, sort, add, insert, and remove items
0001
0002
fruits: “banana”, “apple”, “peach”, “pear”
0003
Write the item at index 3 in fruits
0004
0005
Write: “All fruits, in order:”
0006
Repeat for every fruit
0007
For each fruit in fruits, repeat
0008
Write this fruit’s name
0009
0010
Write: “Fruits in reverse order:”
0011
Reverse the order of the list
0012
Reverse the order of the list
0013
For each fruit in fruits, repeat
0014
Write this fruit’s name
0015
0016
Write: “Fruits in alphabetical order:”
0017
Sort the English fruit names alphabetically
0018
Sort the English fruit names alphabetically
0019
For each fruit in fruits, repeat
0020
Write this fruit’s name
0021
0022
Add “appricot” to the end of fruits
0023
Insert “blueberry” at index 2
0024
Insert “blueberry” at index 2
0025
Remove the item at index 3 (the fourth item)
0026
Remove the item at index 3 (the fourth item)
0027
0028
Write: “The final fruit list:”
0029
For each fruit in fruits, repeat
0030
Write this fruit’s name
Create the list on line 0002. Line 0003 writes the item at index 3: pear. The next loop writes every item in its current order.
Reverse it on line 0012: pear, peach, apple, banana. Reversing changes the order, not the words.
Sort it on line 0018: apple, banana, peach, pear. Sorting arranges the English names alphabetically.
Append “appricot” on line 0022. Appending adds an item at the end. This is the spelling stored in the original example; the usual spelling is “apricot”.
Insert “blueberry” at index 2 on line 0024. It becomes the third item; the later items shift one position to the right.
Remove index 3 on line 0026. Index 3 is the fourth item, now peach. The final list is apple, banana, blueberry, pear, appricot.
Remember: list positions start at 0. Reading an item does not remove it. Reversing and sorting change the order; appending, inserting, and removing change the contents or length. After a change, use the list’s new order when interpreting an index.
You have now met the eight foundations: order, variables, statements, conditions, functions, input/output, loops, and lists. Try tracing an example yourself before looking at its output. When these ideas feel familiar, continue with recursion and turtle classes.
Esta lección es para principiantes sin experiencia. Puedes seguir las instrucciones con el tablero de la tortuga, una moneda y papel. No necesitas saber programar. Empieza por el orden de las instrucciones y añade una idea nueva cada vez.
Los enlaces de ejecución abren un depurador paso a paso. Usa Siguiente y Anterior para observar la instrucción actual, las variables y el tablero o la salida de texto. La página de ejecución mantiene el idioma seleccionado.
0. Seguir instrucciones en orden
Un programa es un conjunto de instrucciones. La computadora las sigue en un orden determinado, normalmente de arriba abajo, salvo que una condición, un bucle o una función cambie el recorrido. El orden importa: la computadora no reorganiza las instrucciones para hacer lo que tú querías decir.
Para jugar a TLAC: usa una moneda pequeña para señalar la instrucción actual. Los números azules, como 0001, indican dónde estás. Las tarjetas amarillas contienen instrucciones; las verdes, comentarios para quien lee.
Una rutina de la mañana, en orden
0001
Llamar a la función: Cepillarme los dientes
0002
Llamar a la función: Peinarme
0003
Llamar a la función: Ir al trabajo
Este orden significa cepillarte los dientes, peinarte y después ir al trabajo. Compáralo con las mismas acciones en otro orden:
Las mismas acciones, otro resultado
0001
Llamar a la función: Cepillarme los dientes
0002
Llamar a la función: Ir al trabajo
0003
Llamar a la función: Peinarme
Aquí sales hacia el trabajo antes de peinarte. Las tres instrucciones siguen presentes, pero la secuencia cambia el resultado. Por eso, revisar el orden es uno de los primeros pasos para encontrar un error de programación.
La lección original también remite a esta charla de Richard Feynman al hablar de cómo las computadoras siguen las instrucciones literalmente.
1. Variables
Una variable es un nombre para un valor guardado. Imagínala como una caja con etiqueta: el nombre indica qué caja usar y su contenido actual es el valor. Una variable puede guardar un número como 5 o texto como «hola». El texto se llama cadena.
Puedes usar nombres como x o last_name. En estos ejemplos los nombres no contienen espacios: last_name es un solo nombre, mientras que «last name» es una frase. Las cadenas se muestran entre comillas para distinguirlas de nombres y números. Por ejemplo, last_name puede guardar «Einstein».
El tipo de valor importa. Un identificador como 123456789 puede escribirse como número, pero «123-45-6789» es texto porque incluye separadores. Elige una representación que conserve la información necesaria, incluidos los ceros iniciales cuando sean importantes.
El valor de una variable puede cambiar. Asignar 3 a x y después asignarle 5 sustituye el valor anterior: ahora x guarda 5. Esta operación se llama asignación. Guarda un valor en un momento concreto del programa; no declara una ecuación matemática que deba ser cierta siempre.
Para jugar a TLAC: escribe los nombres de las variables y sus valores actuales en otra hoja. Tacha el valor anterior cuando una asignación lo cambie.
2. Instrucciones y asignación
Una instrucción o sentencia realiza un paso del programa. Las asignaciones, las llamadas a funciones y las condiciones son ejemplos. Sigue estas tres asignaciones en orden:
Cambiar el valor de x
0001
Asignar 3 a x
0002
Asignar 5 a x
0003
Asignar a x su valor actual + 1
La línea 0001 asigna 3 a x.
La línea 0002 sustituye ese valor por 5.
La línea 0003 lee el valor actual de x (5), suma 1 y guarda 6 en x.
En la notación x = x + 1, primero calcula la expresión de la derecha usando el valor anterior. Después guarda el resultado en la variable de la izquierda. Ese destino a veces se llama lvalue. El valor final es 6; la instrucción no afirma que un número sea matemáticamente igual a sí mismo más uno.
3. Condiciones y bloques
Una condición plantea una pregunta cuya respuesta es verdadera o falsa. Un bloque es un grupo de instrucciones que van juntas. Si la condición es verdadera, ejecuta su bloque; si es falsa, sáltalo. El recuadro de color y la sangría indican qué instrucciones pertenecen al bloque.
Tablero inicial: X=4, Y=9, mirando arriba
Las coordenadas empiezan en 0. X cuenta columnas desde la izquierda y Y cuenta filas desde arriba. X=4 es la quinta columna. «Avanzar» mueve la tortuga una casilla hacia donde mira su cabeza, salvo que se indique otra distancia.
Elegir qué bloques ejecutar
0001
Las tarjetas verdes como estas son comentarios
0002
Los comentarios no cambian lo que hace el programa
0003
Léelos para entender las instrucciones
0004
Si X es mayor que 3, entonces
0005
X es mayor que 3, por lo que
0006
este grupo de instrucciones, dentro del
0007
bloque de color, se ejecutará
0008
Llamar a la función: Avanzar la tortuga 1 casilla
0009
Si X es menor que 3, entonces
0010
Aquí X no es menor que 3, así que
0011
se saltará este bloque
0012
Llamar a la función: Avanzar la tortuga 1 casilla
0013
Asignar 2 a X
0014
Esta asignación mueve
0015
la tortuga a X=2, dos casillas
0016
desde el borde izquierdo (la tercera columna)
0017
Si X es menor que 3, entonces
0018
Después de cambiar X,
0019
X es menor que 3, así que este bloque
0020
se ejecutará
0021
Llamar a la función: Avanzar la tortuga 1 casilla
Las líneas 0001–0003 son comentarios: explican el programa sin mover nada. En la línea 0004, X vale 4, así que «X es mayor que 3» es verdadero. Entra en el bloque y avanza en la línea 0008. X sigue en 4; al subir, Y cambia de 9 a 8.
Después de la línea 0008: X=4, Y=8
En la línea 0009, X sigue valiendo 4, así que «X es menor que 3» es falso. Salta el bloque, incluido el movimiento de la línea 0012. Después, la línea 0013 asigna 2 a X: mueve la tortuga a la tercera columna sin cambiar Y ni su dirección.
Después de la línea 0013: X=2, Y=8
La línea 0017 hace la misma pregunta, pero ahora X vale 2. Esta vez «X es menor que 3» es verdadero, así que ejecuta la línea 0021. La tortuga sube una casilla hasta X=2, Y=7. Una condición usa los valores que existen en el momento de comprobarla.
Tablero final: X=2, Y=7
4. Procedimientos y funciones
Una definición de función da un nombre a un grupo reutilizable de instrucciones. Una llamada a función pide al programa que realice ese grupo. Definir una función no ejecuta su cuerpo. Ya usamos llamadas en la rutina de la mañana:
Llamar a acciones con nombre
0001
Llamar a la función: Cepillarme los dientes
0002
Llamar a la función: Peinarme
0003
Llamar a la función: Ir al trabajo
Ahora define una acción nueva para la tortuga: poner cuatro huevos en un cuadrado. «Poner un huevo» marca la casilla bajo la tortuga. «Girar a la derecha» la rota 90° en sentido horario sin cambiar de casilla. Son acciones incluidas en TLAC; la función que forma el cuadrado es una acción nueva definida por quien programa.
Definir un patrón de huevos y usarlo tres veces
0001
Ejemplo de funciones
0002
Definir un grupo de instrucciones reutilizable:
0003
Definir la función: Poner cuatro huevos en un cuadrado
0004
Llamar a la función: Poner un huevo debajo de la tortuga
0005
Llamar a la función: Avanzar la tortuga 1 casilla
0006
Llamar a la función: Poner un huevo debajo de la tortuga
0007
Llamar a la función: Girar la tortuga a la derecha
0008
Llamar a la función: Avanzar la tortuga 1 casilla
0009
Llamar a la función: Poner un huevo debajo de la tortuga
0010
Llamar a la función: Girar la tortuga a la derecha
0011
Llamar a la función: Avanzar la tortuga 1 casilla
0012
Llamar a la función: Poner un huevo debajo de la tortuga
0013
Los dos giros siguientes
0014
hacen que la tortuga termine
0015
mirando hacia arriba
0016
Llamar a la función: Girar la tortuga a la derecha
0017
Llamar a la función: Girar la tortuga a la derecha
0018
Asignar 0 a X
0019
Mostrar: tablero después de cambiar X
0020
Mostrar el tablero
0021
Llamar a la función: Poner cuatro huevos en un cuadrado
0022
Asignar 5 a X
0023
Mostrar: tablero después de cambiar X
0024
Mostrar el tablero
0025
Llamar a la función: Poner cuatro huevos en un cuadrado
0026
Asignar 8 a X
0027
Mostrar: tablero después de cambiar X
0028
Mostrar el tablero
0029
Llamar a la función: Poner cuatro huevos en un cuadrado
Las líneas 0003–0017 definen la función. Empieza las instrucciones principales en la línea 0018: asigna 0 a X, muestra el tablero y llama a la función en la línea 0021. Sigue su cuerpo y continúa después de la llamada. Luego asigna 5 a X y llámala en la línea 0025. Por último, asigna 8 a X y llámala en la línea 0029.
Cada llamada pone cuatro huevos formando un cuadrado de 2 × 2 y termina mirando hacia arriba. Las tres llamadas forman tres cuadrados: doce casillas marcadas en total. En vez de copiar las mismas instrucciones tres veces, escribimos el patrón una vez y lo reutilizamos. Así el programa es más corto y más fácil de leer o modificar.
Parámetros: dar a una función los datos que necesita
El nombre de una función sigue la misma idea que el de una variable. Algunas funciones también aceptan parámetros: valores que se usan en esa llamada. «Avanzar 5 casillas» da a la función de movimiento una distancia de 5. Otra llamada puede darle otra distancia sin volver a definir las instrucciones.
Las instrucciones de mostrar de este ejemplo ponen un título y muestran el tablero después de cambiar X. Ayudan a ver lo ocurrido; no ponen huevos ni giran la tortuga. Cambiar X mueve la tortuga directamente, mientras que avanzar la mueve hacia donde mira su cabeza.
Volver de una función: cuando termina, continúa en la instrucción que sigue a la llamada. Una instrucción de retorno puede terminar la función antes y también devolver un resultado. Este ejemplo llega al final de su cuerpo sin un retorno explícito. Una función usada principalmente para realizar una acción, en lugar de devolver un valor, a veces se llama procedimiento.
5. Entrada y salida
Salida: mostrar lo que ocurrió
Salida es la información o el resultado visible que produce un programa. En TLAC puede ser un tablero que cambia o algo escrito en papel. Este es un programa muy pequeño:
Avanzar cinco casillas
0001
Un programa muy pequeño
0002
Llamar a la función: Avanzar 5 casillas
Antes: X=4, Y=9
Después: X=4, Y=4
La tortuga empieza mirando hacia arriba. Una distancia de 5 la lleva de Y=9 a Y=4, mientras X sigue en 4. El tablero cambiado es la salida. Un mensaje escrito también puede informar del movimiento y su número.
Entrada: recibir información de un jugador
Entrada es información que recibe el programa. En TLAC, un jugador puede proporcionar entrada moviendo una pieza cuando se le pide. El programa puede leer la posición resultante y recordarla.
Recordar la posición elegida por un jugador
0001
Ejemplo de entrada del usuario
0002
0003
Establecer la posición inicial
0004
Mover la tortuga directamente a X=4, Y=9
0005
Pedir al jugador: coloca la tortuga en la esquina superior izquierda
0006
Respuesta de ejemplo del jugador: mover a X=0, Y=0
0007
Guardar la X de la tortuga en savedX
0008
Guardar la Y de la tortuga en savedY
0009
Pedir al jugador: coloca la tortuga en la esquina inferior derecha
0010
Respuesta de ejemplo del jugador: mover a X=9, Y=9
0011
Mover la tortuga directamente a savedX, savedY
La línea 0004 establece la posición inicial habitual X=4, Y=9. La línea vacía 0002 no hace nada.
La línea 0005 pide al jugador que vaya a la esquina superior izquierda. La línea 0006 registra una respuesta de ejemplo: X=0, Y=0.
Las líneas 0007 y 0008 guardan X e Y en savedX y savedY. Son copias de los valores de ese momento.
Las líneas 0009 y 0010 piden y muestran un movimiento a la esquina inferior derecha, X=9, Y=9.
La línea 0011 devuelve la tortuga a savedX, savedY. En este ejemplo vuelve a X=0, Y=0.
Las instrucciones de respuesta de ejemplo permiten mostrar las acciones del jugador en la ejecución guardada. Al jugar en papel, la persona realiza esas acciones. Un jugador puede elegir otra posición o equivocarse: el programa recuerda la posición que realmente lee, no la que esperabas que eligiera. Esto permite juegos donde una persona hace de computadora y otra controla las piezas.
Un bucle repite un bloque de instrucciones. En lugar de escribir órdenes parecidas muchas veces, indica qué valores usar o cuándo parar. Pregúntate siempre: ¿qué se repite, qué cambia y cuándo termina?
Contar hacia arriba con un bucle
Usar cada número del 5 al 9
0001
Contar del 5 al 9, ambos incluidos
0002
Para cada i en 5, 6, 7, 8, 9, repetir
0003
Mover la tortuga directamente a X=i, Y=i
0004
0005
Escribir: «He contado del 5 al 9»
En la línea 0002, i toma los valores 5, 6, 7, 8 y 9. Para cada valor, la línea 0003 usa i en ambas coordenadas. La tortuga visita (5,5), (6,6), (7,7), (8,8) y (9,9), formando una diagonal. Se incluyen 5 y 9; no se incluye 10. El mensaje de la línea 0005 está fuera del bucle y se escribe una sola vez al terminar.
Una cuenta atrás sirve para un lanzamiento de cohete o cualquier tarea cuya cantidad pendiente disminuye. Aquí la cuenta controla cuánto avanza la tortuga cada vez.
Avanzar 3, luego 2, luego 1 y luego 0 casillas
0001
Cuenta atrás del 3 al 0
0002
Para cada i en 3, 2, 1, 0, repetir
0003
Llamar a la función: Avanzar i casillas
El contador empieza en 3 y disminuye en 1 cada vez, incluido el valor final 0. Los movimientos suman 3 + 2 + 1 + 0 = 6 casillas. Avanzar cero casillas deja a la tortuga en su sitio. Desde X=4, Y=9 mirando arriba, termina en X=4, Y=3.
Hacer primero y comprobar después: patrón do-while
A veces el cuerpo debe ejecutarse al menos una vez antes de decidir si continuar. Este ejemplo repite, aumenta un contador y sale cuando este supera un límite. Tiene el comportamiento de un bucle do-while: primero ejecutar el cuerpo y después decidir si repetir.
Parar cuando el contador supere su límite
0001
Repetir primero y comprobar después si hay que parar
0002
Asignar 1 a n1
0003
Asignar 3 a n2
0004
Asignar 1 a step
0005
0006
El cuerpo se ejecutará al menos una vez
0007
Repetir hasta que una instrucción detenga este bucle
0008
Escribir: «El valor de n1 es» seguido de n1
0009
1. Ejecutar la acción repetida
0010
Llamar a la función: Avanzar n1 casillas
0011
0012
2. Aumentar el contador en step
0013
Sumar step a n1 y guardar el resultado en n1
0014
0015
3. Comprobar si n1 ha superado n2
0016
Si n1 es mayor que n2, salir del bucle
0017
Si n1 es mayor que n2, entonces
0018
Salir del bucle más interno
0019
Escribir: «n1 ha superado el límite»
Los valores iniciales son n1=1, n2=3 y step=1. Cada vuelta escribe n1, avanza n1 casillas y suma step a n1. Por tanto, las distancias son 1, 2 y 3. Tras la tercera vuelta n1 vale 4, así que «n1 es mayor que n2» es verdadero y se sale del bucle. El mensaje final está fuera del bucle.
Observa que aquí el contador aumenta. La condición comprueba cuándo parar: salir si n1 es mayor que n2; en caso contrario, repetir. Sin un cambio que finalmente cumpla la condición de parada, el bucle podría seguir para siempre.
Un bucle puede contener otro. El bucle exterior elige una fila y el bucle interior recorre todos los elementos de esa fila. Aquí i y j toman los valores 1, 2 y 3.
Crear una tabla de multiplicar de 3 × 3
0001
Para cada i en 1, 2, 3, repetir
0002
Empezar con un texto de salida vacío
0003
0004
El bucle interior cambia el segundo número
0005
Para cada j en 1, 2, 3, repetir
0006
Añadir cada multiplicación a la fila de salida
0007
Añadir «i × j = su producto» a output, con espacios
0008
0009
Mostrar la fila completa
0010
Mostrar el texto de output
0011
0012
Separar las filas con líneas en blanco
0013
Mostrar líneas en blanco
Para i=1, el bucle interior pasa por j=1, j=2 y j=3 antes de que i cambie. Luego se usan los mismos tres valores de j para i=2 y otra vez para i=3. Hay 3 × 3 = 9 multiplicaciones. Empieza cada fila con un texto vacío, añade sus tres ecuaciones y muestra la fila completa.
Definir la función: Hacer una fila de la pirámide — entradas: ch, times, triangle_width
0005
Empezar con un texto de salida vacío
0006
0007
1. Primer bucle interior: añadir espacios
0008
Incluir el último valor en esta repetición
0009
Asignar triangle_width − times a repeat_end
0010
Repetir contando de 0 a repeat_end, ambos incluidos
0011
Añadir un espacio a output
0012
0013
2. Segundo bucle interior: añadir estrellas
0014
Asignar times × 2 − 2 a repeat_end2
0015
Repetir contando de 0 a repeat_end2, ambos incluidos
0016
Añadir el carácter ch a output
0017
0018
Mostrar el texto de output
0019
0020
3. Bucle exterior: crear las filas 1 a 5
0021
Usar los números de fila 1, 2, 3, 4, 5
0022
Para cada i en 1, 2, 3, 4, 5, repetir
0023
Hacer una fila de la pirámide — ch: *, times: i, triangle_width: 5
El bucle exterior llama cinco veces a la función que crea una fila. Le pasa el carácter estrella como ch, el número de fila como times y 5 como triangle_width. Dentro, el primer bucle añade espacios y el segundo estrellas. Los dos bucles interiores se ejecutan uno después del otro. Después se muestra la fila completa.
Fila
Espacios
Estrellas
1
5
1
2
4
3
3
3
5
4
2
7
5
1
9
*
***
*****
*******
*********
En el juego de mesa, mostrar texto significa escribir los caracteres en papel, conservando los espacios para alinear la figura. Este programa combina funciones, parámetros, cuentas y varios bucles.
Una lista guarda varios valores en orden. Cada valor es un elemento. Un índice indica su posición. En estos ejemplos se empieza a contar en 0: el primer elemento tiene índice 0, el segundo índice 1, y así sucesivamente. Los arreglos son otra forma de organizar valores con índices; aquí usaremos listas.
Para cada elemento: seguir una lista de órdenes
Un bucle para cada elemento recorre la lista en orden. La siguiente lista describe una ruta de la tortuga. Toma una orden, decide qué significa, realiza la acción y pasa a la siguiente. La lista se convierte en datos que describen un pequeño programa.
Llamar a la función: Girar la tortuga a la derecha
0010
Si no, si la orden es izquierda, entonces
0011
Llamar a la función: Girar la tortuga a la izquierda
La lista de la línea 0002 tiene ocho órdenes: avanzar, avanzar, derecha, avanzar, avanzar, izquierda, avanzar, avanzar. El bucle empieza en la línea 0005. Las condiciones eligen la acción correspondiente a la orden actual. Desde X=4, Y=9 mirando arriba, dos avances llegan a (4,7); girar a la derecha y avanzar dos veces lleva a (6,7); girar a la izquierda y avanzar dos veces lleva a (6,5), mirando arriba.
Ahora usaremos una lista de frutas. Conservamos los valores guardados en inglés para que el orden alfabético y el resultado guardado coincidan en las tres versiones de la lección. La lista inicial contiene banana (banana), apple (manzana), peach (melocotón) y pear (pera).
Índice
Valor guardado
0
banana
1
apple
2
peach
3
pear
La notación fruits[0] significa el elemento del índice 0: banana en la lista inicial. fruits[3] es el cuarto elemento: pear. Un índice identifica una posición, así que la palabra que ocupa esa posición puede cambiar al reorganizar la lista.
Invertir, ordenar, añadir, insertar y eliminar elementos
0001
0002
fruits: «banana», «apple», «peach», «pear»
0003
Escribir el elemento de fruits en el índice 3
0004
0005
Escribir: «Todas las frutas, en orden:»
0006
Repetir para cada fruta
0007
Para cada fruta de fruits, repetir
0008
Escribir el nombre de esta fruta
0009
0010
Escribir: «Frutas en orden inverso:»
0011
Invertir el orden de la lista
0012
Invertir el orden de la lista
0013
Para cada fruta de fruits, repetir
0014
Escribir el nombre de esta fruta
0015
0016
Escribir: «Frutas en orden alfabético:»
0017
Ordenar alfabéticamente los nombres ingleses de las frutas
0018
Ordenar alfabéticamente los nombres ingleses de las frutas
0019
Para cada fruta de fruits, repetir
0020
Escribir el nombre de esta fruta
0021
0022
Añadir «appricot» al final de fruits
0023
Insertar «blueberry» en el índice 2
0024
Insertar «blueberry» en el índice 2
0025
Eliminar el elemento del índice 3 (el cuarto)
0026
Eliminar el elemento del índice 3 (el cuarto)
0027
0028
Escribir: «La lista final de frutas:»
0029
Para cada fruta de fruits, repetir
0030
Escribir el nombre de esta fruta
Crear la lista en la línea 0002. La línea 0003 escribe el elemento del índice 3: pear. El siguiente bucle escribe todos los elementos en su orden actual.
Invertirla en la línea 0012: pear, peach, apple, banana. Se cambia el orden, no las palabras.
Ordenarla en la línea 0018: apple, banana, peach, pear. La ordenación coloca los nombres ingleses alfabéticamente.
Añadir «appricot» al final en la línea 0022. Añadir al final conserva los elementos anteriores. Esa es la escritura del ejemplo original; la palabra habitual es «apricot» (albaricoque).
Insertar «blueberry» (arándano) en el índice 2 en la línea 0024. Pasa a ser el tercer elemento; los posteriores se desplazan una posición a la derecha.
Eliminar el índice 3 en la línea 0026. Es el cuarto elemento, que ahora es peach. La lista final es apple, banana, blueberry, pear, appricot.
Recuerda: las posiciones empiezan en 0. Leer un elemento no lo elimina. Invertir y ordenar cambian el orden; añadir, insertar y eliminar cambian el contenido o la longitud. Después de un cambio, usa el nuevo orden al interpretar un índice.
Ya has conocido los ocho fundamentos: orden, variables, instrucciones, condiciones, funciones, entrada/salida, bucles y listas. Intenta seguir un ejemplo antes de mirar su resultado. Cuando te resulten familiares, continúa con la recursión y las clases de tortugas.