Studyfin Studyfin ✨ Sign up free

Functions

Grade 10 · Coding · Free lesson

Hey there! Ready to level up your coding skills? Today, we will explore how functions help us organize our code.

In programming, a function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, we group it into a function and call it whenever we need it.

To design a program, we break a big problem down into smaller subproblems. We can write a function for each subproblem, which makes our code clean, organized, and easy to read.

Big ProblemSubproblem ASubproblem B

We can also use nested loops inside our functions to handle repetitive tasks. A nested loop is simply a loop running inside another loop, which is perfect for working with grids or coordinates.

Nested Loops Visit Every Cell
✏️ Worked example

Let's design a program to draw a 3x3 grid of stars using a function with nested loops. We will break this down into clear, logical steps.

  1. 1. Identify the subproblem: We need to print a single row of stars, and we need to repeat this process to make multiple rows.
  2. 2. Define the function: We name our function 'draw_grid' so its purpose is clear to anyone reading our code.
  3. 3. Write the outer loop: This loop runs 3 times, once for each row of our grid.
  4. 4. Write the inner loop: Inside the outer loop, we create another loop that runs 3 times to print 3 stars side-by-side in that row.
  5. 5. Call the function: We run 'draw_grid()' in our main program to execute the nested loops and display our completed grid.
Want the full interactive lesson — quiz, animations, and Finn cheering them on?

More Coding lessons