computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🏠

🎓

⏱ 20 min

Free

Build Functions

Name a build once, then reuse it anywhere in your world.

🎯 What you will learn

  • A function is a named build
  • Inputs change the size
  • Reusing a function saves time

👋 Let’s get started!

Imagine building the same wall in 10 places. With a function, you name the build once and call it wherever you need it. Give it inputs for width and height, and it changes the size each time. 🏠

🪜 Step by step

1. 🏷️ Name the build

def starts a function. Give it a name and inputs in brackets.

def build_wall(width, height):
    print("Wall", width, "by", height)
2. 🧱 Build with a loop

Use a loop inside the function to place each row.

def build_wall(width, height):
    for row in range(height):
        print("#" * width)
3. 🔁 Reuse it

Call your function as many times as you like.

build_wall(4, 2)
build_wall(2, 3)

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

Wall builder

def build_wall(width, height):
    for row in range(height):
        print("#" * width)

build_wall(4, 2)
print()
build_wall(2, 3)

🎨 Unplugged activity

🏠 Write your own build function on paper: name it, give it width and height inputs. Then call it for 3 different houses.

Build a house

def build_wall(width, height):
    for row in range(height):
        print("#" * width)
build_wall(3, 1)
build_wall(3, 2)

📖 Key words

Tap a card to flip it over!

def
Starts a function 🏷️
Input
Information you give a function 🎁
Reuse
Using the same code again ♻️

🏆 Challenge

Call build_wall with width 5 and height 1. Press ▶ Run.

Challenge

def build_wall(width, height):
    for row in range(height):
        print("#" * width)

Knowledge Check Quiz

  1. What does def do?
  2. What do the inputs 4 and 2 change?
  3. Why reuse a function?
← Previous lesson
Next lesson →