โ†Previous page

07FUNCTIONS ยท METHODS

Boxes that come with the value.

Some functions belong to a value. You call them with a dot: value.job(). They are called methods.

IN REAL LIFE

Things that know their own jobs.

You do not teach these tricks again. You say who, then a dot, then the job.

Your dog's tricks

Rocky knows how to sit. You say: Rocky, sit! In Python: rocky.sit()

The TV remote

The volume button belongs to the TV: tv.volume_up()

The backpack zipper

backpack.open() opens this backpack, not your friend's.

LOOK FIRST

Who, dot, job.

The dot joins them

Write the value, a dot, and the method: name.upper()

Text has its own

"hi".upper() gives back "HI". "cat".replace("c", "h") gives back "hat".

Lists have their own

toys.append("ball") does a job: it puts ball at the end of the list.

STEP BY STEP

Ask the boxes with a dot.

Some methods do a job, like def. Some give something back, like return.

toys = ["car", "doll"]A list box with 2 toys, like in Boxes of all kinds.
toys.append("ball")The list's own job: add ball at the end. It gives nothing back.
print(toys)Shows ['car', 'doll', 'ball']
name = "pybot"A text box.
print(name.upper())upper gives back a new text in capitals: PYBOT

RUN IT

Fill PyBot's lunch box.

Guess first. Then run real Python and check.

1

Guess the result

snacks = ["apple"] snacks.append("banana") snacks.append("grapes") print(snacks)

What will Python show?

snacks.pyREAL PYTHON
OUTPUT
Ready. Press Run Python.
Python runs here thanks to Pyodide โ™ฅ

Pyodide 314.0.3 runs CPython in your browser with WebAssembly.

Open-source under the Mozilla Public License 2.0. License

Now change one thing: Add one more append line with your favorite snack.

YOUR TURN

Who, dot, job.

Try each tiny question. A wrong answer becomes something to review.

0Completed
9Not tried
0Review
01

Rocky, sit!

Rocky the dog knows how to sit. PyBot wants Rocky to sit.

How would Python say it?

02

The joining symbol

Which symbol joins a value to its method?

03

Big letters

print("hi".upper())

What does Python show?

04

Swap a letter

print("cat".replace("c", "h"))

What does Python show?

05

A new pet

pets = ["cat"] pets.append("dog") print(pets)

What does Python show?

06

Count the letters

print("banana".count("a"))

What does Python show?

07

Not my trick

age = 9 print(age.upper())

What happens?

08

Fix PyBot's code

PyBot called upper like a normal function, but upper belongs to the text. Use the dot. Make it show: HELLO

Goal output
HELLO
OUTPUT

Your work is saved here.

Want a fresh start? Clear only this page.

!
BIG IDEA

A method is a function that belongs to a value.

Who, dot, job. Some methods do a job, some give something back, just like the boxes you made with def.