Lesson / Lección 1: Introduction to Functions

Reeborg Progress
15%

In this Exercise we are going to be introducing commands/functions. Commands are tasks you give a computer or in this case, Reeborg the Robot, to complete. Functions are a group of commands to complete a specific task. For example, cooks use recipes from cookbooks to make food. These recipes give them instructions on how to complete a task, namely, baking a cake or boiling pasta. A command would be the individual steps in the recipe while a function is a set of steps to complete a task, such as boiling the water for the pasta or mixing ingredients for the cake. Similarly, the commands in a function give instructions that direct the computer in completing a task. You are telling it what to do.

Here are some formal definitions if they are helpful for guiding instruction.
Command: A command is an instruction given by a user telling a computer to do something, such a run a single program or a group of linked programs.
Program: A program is a sequence of instructions that is understandable by a CPU (central processing unit), the main logic unit of a computer. (http://www.linfo.org/program.html)

When you write your code in the Python Code screen and execute it (press the play button), the code is read from top to bottom, line by line. Each also command gets its own line, the computer cannot read multiple commands written on each line.

Click on the picture to get taken to the Reeborg Lesson.

Exercise: Home 2

Guiding Questions:

  • In Home 1, we want to write a program with commands to help Reeborg reach home. What type of instruction would be helpful to do that?
  • What type of action do we want Reeborg to take?

Let’s learn about the move() command. This command moves Reeborg one unit in the grid world, in the direction that Reeborg is facing. For example, in the picture above, Reeborg is facing down, so when we run the move() Reeborg will move down.

Now that we learned the first command: move(), let’s create our first program. In the editor screen enter the commands you want Reeborg to complete.

Exercise: Home 3

Guiding Questions:

  • How do we get Reeborg to move in a different direction/face a different way?

This exercise introduces the turn_left() command. This command allows Reeborg to change direction so that they can move in a different direction. Note: Make sure you are noticing which way Reeborg is facing. Reeborg turns to its left and necessarily our left. Some find it helpful to stand up and face the same way Reeborg is facing and see if turn_left() will turn Reeborg the current way.

Exercise: Newspaper 0

Guiding Questions:

  • We have a turn_left() command, but no turn right command. There are times where programming languages don’t have a direct command for something you want to do. In this case we can define a new function. How would we defined a turn_right() function using turn_left()?

Remember, a function is a group of commands that complete a specific task. In this case turn_left() is a command while turn_right() would be a function with 3 turn_left() commands to turn right.

In this case, that would look something like this:

def turn_right():
    turn_left()
    turn_left()
    turn_left()

It is important to have the def statement to let the computer know you are making your own function. Afterwards, give a name to the function, turn_right() and end this line with a colon. Now we have the function named, but we also need to give it commands, underneath you will put the commands you want completed by the functions. Make sure that those commands are indented so the computer knows that those commands belong to the function.

  • Note: When you are naming a function, spaces are not accepted. If you want to put a space, use an underscore for this.
  • Functions that are defined must be defined before the main body of the program (before your other code), otherwise they will not be recognized

This exercise also introduces the commands take() and put(). Reeborg can pick up objects with take() and put down objects it is carrying with put(). Reeborg can only pick up objects when it is standing on the cell the object is in. Reeborg can only put down an object if it is already carrying the object.

Note that though it is not explicit in the task instructions, Reeborg must put the newspaper down on the goal and then return to the starting point.


En este ejercicio vamos a presentar funciones. Las funciones son ejercicios que le da a una computadora o en este caso, Reeborg el Robot, para completar. Las funciones son un grupo de comandos para completar una ejercicio específica. Por ejemplo, los cocineros usan recetas de cocina para hacer comida. Estas recetas les dan instrucciones sobre cómo completar un platillo como hornear un pastel o hervir pasta. Una funcion sería los pasos individuales en la receta, como hervir el agua para la pasta o mezclar ingredientes para el pastel. Del mismo modo, las pasos individuales de funciones dan instrucciones que dirigen a la computadora para completar un ejercicio. Le estás diciendo qué hacer.

Aquí hay algunas definiciones formales si son útiles para guiar la instrucción.
Función: Una función es una instrucción dada por un usuario que le dice a una computadora que haga algo, como ejecutar un solo programa o un grupo de programas vinculados.
Programa: Un programa es una secuencia de instrucciones que es comprensible por una CPU (unidad central de procesamiento), la unidad lógica principal de una computadora. (http://www.linfo.org/program.html)

Cuando escribe su código en la pantalla de Python Code y lo ejecuta (presione el botón de reproducción), el código se lee de arriba a abajo, línea por línea. Cada función también tiene su propia línea, la computadora no puede leer varios comandos escritos en cada línea.

Haga clic en la imagen para ser llevado a la Lección Reeborg.

Ejercicio: Home 2

Preguntas orientadoras:

  • En Inicio 1, queremos escribir un programa con comandos para ayudar a Reeborg a llegar a casa. ¿Qué tipo de instrucción sería útil para hacer eso?
  • ¿Qué tipo de acción queremos que Reeborg tome?

Aprendamos sobre la función move(). Esta función mueve a Reeborg una unidad en el mundo de la cuadrícula, en la dirección a la que se enfrenta Reeborg. Por ejemplo, en la imagen de arriba, Reeborg está boca abajo, por lo que cuando ejecutamos el movimiento move() Reeborg se moverá hacia abajo.

Ahora que aprendimos el primer función: move(), creemos nuestro primer programa. En la pantalla del editor, ingrese los comandos que desea que Reeborg complete.

Ejercicio: Home 3

Preguntas orientadoras:

  • ¿Cómo hacemos que Reeborg se mueva en una dirección diferente?

Este ejercicio presenta la función turn_left(). Esta función permite a Reeborg cambiar de dirección para que pueda moverse en una dirección diferente. Nota: Asegúrese de estar notando hacia dónde se dirige Reeborg. Reeborg gira a su izquierda y no es necesariamente a nuestra izquierda. A algunos les resulta útil pararse y mirar de la misma manera que Reeborg está mirando y ver si turn_left() convertirá a Reeborg de la manera actual.

Ejercicio: Newspaper 0

Preguntas orientadoras:

  • Tenemos una función turn_left(), pero no tenemos la función que girar a la derecha. Hay momentos en que los lenguajes de programación no tienen una función directo para algo que quieres hacer. En este caso podemos definir una nueva función. ¿Cómo definiríamos una función turn_right() usando turn_left()?

Recuerde, una función es un grupo de funciones que completa un objectivo específica. En este caso, turn_left() es una función, mientras que turn_right() sería una función con 3 llamadas a turn_left() para girar a la derecha.

En este caso, se vería así:

def turn_right():
    turn_left()
    turn_left()
    turn_left()

Es importante tener la declaración def para que la computadora sepa que está haciendo su propia función. Luego, asigne un nombre a la función, turn_right() y finalice esta línea con dos puntos. Ahora tenemos la función nombrada, pero también tenemos que darle instrucciones, debajo colocará los comandos que desea que completen las funciones. Asegúrese de que esas funciones estén sangrados para que la computadora sepa que esos comandos pertenecen a la función.

  • Nota: Cuando nombra una función, no se aceptan espacios. Si quieres poner un espacio, usa un guión bajo para esto.
  • Las funciones que se definen deben definirse antes del cuerpo principal del programa (antes de su otro código), de lo contrario no se reconocerán

Este ejercicio también presenta las funciones take() y put(). Reeborg puede recoger objetos con take() y colocar objetos que lleva con put(). Reeborg solo puede levantar objetos cuando está parado en la celula en la que se encuentra el objeto. Reeborg solo puede dejar un objeto si ya está cargando el objeto.

Tenga en cuenta que, aunque no está explícito en las instrucciones de la objectivo, Reeborg debe dejar el periódico en la portería y luego volver al punto de partida.