First Functions

This is part of “An intro to Coding” series of posts, with content from the Enki app. If you stumbled upon this, you can start from the beginning.

It's Saturday afternoon, and you're ready for a grilled cheese sandwich 🧀. Here is the recipe¹.

Instead of making the sandwich yourself, you remembered that you have a robot sitting in your garage that can do the job for you.

Let's write some code to tell our robot how to make a sandwich!

To get us started, start with the preparation of the ingredients first.

The function above is called prepare_ingredients and takes in cheese, grater, bowl, and bread as inputs and returns a cheese_bowl and sliced_bread as output.

prepare_ingredients calls two functions within its body:

  • grate_cheese_in_the_bowl with grater, cheese and bowl as the input and stores the output into the cheese_bowl variable
  • slice_the_bread with bread as the input and stores the output into the liced_bread` variable

Let's continue preparing the sandwich-making instructions for our robot by writing a function to perform the second step of our recipe¹ - building out the sandwich from the ingredients.

Whew! That's a lot of code!

Computers are 100% literal² like that. We have to spell out everything exactly for them. Otherwise, they won't understand what we're asking of them.

For example, in the code above, take a look at the last two lines of the function body:

If you forgot to save the output of combine_slices into the variable sandwich:

The computer wouldn't know what to do! It doesn't know what sandwich variable is unless you tell it.


Footnotes

[1] The recipe says:

Ingredients:

  • cheese
  • bread
  • butter
  • plate
  • bowl

Instructions:

1. prepare the ingredients
 - Grate the cheese in a bowl
 - Cut the bread into slices

2. build the sandwich
 - Butter the bread on both sides
 - Add the cheese to the sandwich

3. grill the sandwich
 - Preheat a pan
 - Fry the sandwich for three minutes on each side (or until golden brown)

[2] In some languages, instructions usually end with a semicolon ;.

This means that the instruction:

will not work in those languages!

We have to end it with a ; like this:

Andrei Calabangiu

Content Manager

About Enki

  • AI-powered, customized 1:1 coaching
  • Fully customized to team needs
  • Pay only for active learners and results

More articles