Lesson 2 of 10
A function that always does exactly the same thing is limited. Parameters let you pass data in.
def greet(name):
print(f"Hello, {name}!")
greet("Ada")
greet("Grace")
name is a parameter — a variable that exists inside the function. "Ada" is an
argument — the actual value you pass when calling. The parameter is the slot; the argument
is what you put in it.
Multiple parameters
Separate them with commas. Arguments are matched to parameters by position.
def describe(name, age):
print(f"{name} is {age} years old.")
describe("Ada", 36)
Get the order wrong and you get nonsense — describe(36, "Ada") would print "36 is Ada years
old." You can be explicit with keyword arguments, which work in any order:
def describe(name, age):
print(f"{name} is {age} years old.")
describe(age=36, name="Ada")
Returning a value
Printing shows something to the user. Returning hands a value back to the code that called the function, so it can be stored, reused, or passed along.
def add(a, b):
return a + b
result = add(3, 5)
print(result)
print(add(10, 20))
This distinction matters more than it first appears:
def add_and_print(a, b):
print(a + b)
def add_and_return(a, b):
return a + b
x = add_and_print(3, 5)
y = add_and_return(3, 5)
print(x)
print(y)
add_and_print displays 8 but gives back nothing, so x is None. add_and_return gives back
8, so y is 8 and you can keep working with it. As a rule: functions should return values;
let the caller decide whether to print.
return exits immediately
Nothing after a return runs:
def check(number):
if number > 0:
return "positive"
return "zero or negative"
print(check(5))
print(check(-3))
Because return exits, you often don't need an else.
Returning multiple values
Return several values separated by commas and Python packs them into a tuple — which you can unpack, exactly as in lesson 3.4:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
print(low)
print(high)
Try it yourself
Write add(a, b) that returns the sum, and multiply(a, b) that returns the product. Print
both results.
Checkpoint
- Parameters are the named slots; arguments are the values passed in.
- Positional arguments match by order; keyword arguments match by name.
returnsends a value back and exits the function immediately.- A function with no
returngives backNone. - Prefer returning over printing — the caller can always print.
Questions about this lesson
Log in to ask a question.