Studyfin Studyfin ✨ Sign up free

Functions

Grade 9 · Coding · Free lesson

Hey there! Today we are going to explore functions, which are like mini-machines that run your code whenever you need them.

In coding, a function is a named block of code that does a specific job. Instead of writing the same steps over and over, you write them once inside a function and call it whenever you want.

ai generated

Think of a function like a juice blender. You put ingredients in, which are called inputs or parameters. The blender runs its program, and then it gives you delicious juice, which is the output or return value.

How a Function Works Input (Fruit) Output (Juice)

To design a program with nested loops inside functions, we break down a big problem into smaller subproblems. For example, we can make a function that draws one row of stars, and then call it inside a loop to draw a whole grid.

Nested Loop Output (Grid of Stars)
✏️ Worked example

Design a text-based program that prints a 3x3 grid of stars using a function with nested loops.

  1. Identify the subproblems: We need to print a single star, print a row of stars, and repeat that row multiple times.
  2. Define a function named 'print_row' that uses a loop to print 3 stars side-by-side.
  3. Create a second loop outside the function that calls 'print_row' exactly 3 times.
  4. Run the program to see the nested loops work together to create a perfect 3x3 grid of stars.
math
Want the full interactive lesson — quiz, animations, and Finn cheering them on?

More Coding lessons