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
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:
def star_for(name):
print(name + " gets a star!")
star_for("Mia")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.
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:
def star_for(name, count):
print(name + " gets", count, "stars!")
star_for("Mia", 3)
star_for("Leo", 5)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.
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:
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))
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.
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.