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

← All lessons · 🧑‍💻 Coding Academy

🛠️

🎓

⏱ 25 min

Free

Functions: Your Own Commands

Create reusable commands with def, give them inputs and get answers back with return.

🎯 What you will learn

  • Define functions with def
  • Pass in parameters
  • Send back results with return

👋 Let’s get started!

print() and len() are functions someone else built. Now YOU get to invent commands! Functions let you write code once and use it again and again. 🛠️

🪜 Step by step

1. 🛠️ def

def makes a function. The indented code runs when you call it.

def cheer():
    print("Go team! 📣")

cheer()
cheer()
2. 📥 Parameters

Parameters let you send information in.

def greet(name):
    print("Hello, " + name + "!")

greet("Ana")
greet("Raj")
3. 📤 return

return sends an answer back.

def double(n):
    return n * 2

print(double(21))

🧪 Try it!

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

Temperature converter

def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32

for c in [0, 20, 37, 100]:
    print(c, "°C =", to_fahrenheit(c), "°F")

Area function

def area(width, height):
    return width * height

result = area(4, 5)
print(result)

📖 Key words

Tap a card to flip it over!

Function
A named, reusable block of code 🛠️
def
Starts a function definition ✍️
Parameter
An input to a function 📥
return
Sends a result back 📤

🏆 Challenge

Write a function square(n) that returns n times n. The code below should print 49.

Challenge

def square(n):
    

print(square(7))

Knowledge Check Quiz

  1. What prints?
  2. Which keyword creates a function?
  3. What does return do?
← Previous lesson
Next lesson →