Syllabus Lesson 20 of 239 · Functions
Functions

Parameters: Passing Data In

A function gets more useful when you can feed it data. The names inside the parentheses are parameters (the slots), and the values you pass when calling are arguments (what fills the slots).

def greet(name):
    return f"Hi {name}"

print(greet("Sam"))   # Hi Sam
print(greet("Ada"))   # Hi Ada

Here name is a parameter. When you call greet("Sam"), the argument "Sam" becomes name inside the function.

You can have several parameters, separated by commas. By default they fill in order (this is positional):

def add(a, b):
    return a + b

print(add(2, 3))   # 5  (a=2, b=3)

Order matters with positional arguments. add(2, 3) and add(3, 2) happen to match here, but greet("Hi", "Sam") would put the wrong value in each slot. Pass arguments in the same order as the parameters.

Your turn

Define a function area that takes two parameters, width and height, and returns their product (width * height). It should not print anything. Example: area(4, 5) returns 20.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output