Learning LibraryCore Coding LibraryKids

Arguments: feed values into a function

The same function can do different things each time — you just feed it different arguments. One draw_star command, a new star every call.

The big idea

Arguments are the values you hand a function inside its ( ), and they change what the function does.

See it in code

1Start simple

An argument is a value you hand a function inside its ( ). Here star_for takes one argument, name, and uses it. Pass a different name and you get a different message:

python
def star_for(name):
    print(name + " gets a star!")

star_for("Mia")
Run it — the name you pass in shows up in the message:
Mia gets a star!

name is the argument. We handed it "Mia", and the function used it. Hand it something else and the message changes.

2A step further

A function can take more than one argument. star_for now takes a name and a count. Two calls with different values give two different results:

python
def star_for(name, count):
    print(name + " gets", count, "stars!")

star_for("Mia", 3)
star_for("Leo", 5)
Run it — same function, two sets of arguments:
Mia gets 3 stars!
Leo gets 5 stars!

Two arguments this time, and their order matters: name first, then count. Swap them and the message comes out wrong.

3In our world

Now in the art studio. Our draw_star command takes three arguments — x, y, and color. Same recipe every time, but each call passes different values, so each star is different:

python
from art import Canvas, star

screen = Canvas.create()
Canvas.fill(screen)

def draw_star(x, y, color):
    star(screen, x, y, size=70, color=color)

draw_star(140, 180, (255, 99, 132))
draw_star(250, 300, (75, 200, 190))
draw_star(360, 180, (255, 205, 86))
Run it — three calls, three different stars:
Three stars on a dark canvas at different spots: a pink one and a gold one high up, a teal one lower in the middle.

We wrote draw_star once. The three arguments — a spot and a color — made each call draw somewhere new. Change an argument, change the star.

The same idea, everywhere

Arguments make one function flexible. greet(name) says hello to anyone. roll(sides) rolls any die. move(steps) walks any distance. You write the steps once, then let the arguments fill in the details.

Try it yourself

Add a fourth star of your own with draw_star(...). Pick a spot and a color like (153, 102, 255). Then add a size argument to the function so each star can be big or small.

The common mistake

Passing arguments in the wrong order. draw_star expects x first, then y, then color. Swap x and y by accident and your star lands in the wrong place. Order matters.

What it unlocks

Once a function takes arguments, it can also hand an answer back with return values, and you can use colors as numbers with RGB color.

Older, or want more depth? Read the Teens version →