INTRODUCTION
Recipe cards
def writes a function. Its name runs it.
press Enter ↵
🐍 main.py
Ctrl + Enter runs it too. Esc, then Tab, leaves the code.
Output

Press ▶ Run to see what your program does.

Lesson 39: Functions

Level 5, Python Thinks and Repeats. Write a recipe once with def, use it again and again. The new word: function. It follows lesson 38, Lists. Next comes lesson 40, Import a toolbox (random).

What the lesson explains

Recipe cards. def writes a function. Its name runs it.

def, then use it. name in the brackets is filled in each time. On the card: def greet(name):

What you do first

Call it again. Greet Mia too. The editor opens with: def greet(name): / print("Hello, " + name + "!") / / greet("Ada"). One way to write it: def greet(name): / print("Hello, " + name + "!") / / greet("Ada") / greet("Mia"). It prints: Hello, Ada! / Hello, Mia!.

The code on the screen

def, then use it. The editor shows 5 lines: def greet(name): / print("Hello, " + name + "!") / / greet("Ada") / greet("Sam"). Run it, and it prints "Hello, Ada!", "Hello, Sam!".

What you practise

Try it, "Call it again": Greet Mia too. The editor opens with: def greet(name): / print("Hello, " + name + "!") / / greet("Ada"). One way to write it: def greet(name): / print("Hello, " + name + "!") / / greet("Ada") / greet("Mia"). It prints: Hello, Ada! / Hello, Mia!.

Try it, "Hand an answer back": Finish double so it prints 14. The editor opens with: def double(n): / / / print(double(7)). One way to write it: def double(n): / return n * 2 / / print(double(7)). It prints: 14.

Challenge, "Your own function": Write square and print square(5). One way to write it: def square(n): / return n * n / / print(square(5)). It prints: 25.

What PlayBuddy and PlayType say

PlayBuddy: "A function is a recipe card. Write it once, use it again and again."

PlayType: "A function can hand an answer back. That is called returning."

Help in every lesson

Everything happens on a pretend computer in your browser, so nothing touches your real files. PlayBuddy and PlayType stand beside the board, cheer you on and say when it is your turn.

A green ring shows where to click the first time. After that you do it on your own, and if you slip twice the ring comes back.

Stars

The lesson has 3 things to do. Up to one slip in ten gives three stars, up to one in four gives two, and finishing always gives at least one. Stars and progress are saved in this browser only; there is no account.

About DayOneCode

DayOneCode is an independent learning site, not affiliated with or endorsed by Anthropic. Claude and Claude Code are trademarks of Anthropic.