Functions: parameters, return and defaults
Write your own Python functions with def: take parameters, give a result back with return, add default values and explain the function in a docstring.
A function is a piece of code with a name, which you can run (call) whenever you need it. def makes one:
def greet(name):
print(f"Hi, {name}!")
greet("Sam")
greet("Noor")name is a parameter: a name that, inside the function, stands for whatever value the caller passed in (the argument).
return
print shows a value; return hands it back to whoever called the function, so they can keep using it:
def area(width, height):
return width * height
kitchen = area(3, 4)
print(kitchen + area(2, 2)) # 16return also ends the function at once. A function that never reaches a return gives back None: try print(greet("Sam")) above and see None printed after the greeting.
Defaults and keyword arguments
A parameter with = has a default, used when the caller leaves it out. Callers can also name arguments, in any order:
def brew(tea, minutes=3, milk=False):
return f"{tea}, {minutes} min" + (", with milk" if milk else "")
print(brew("green"))
print(brew("black", 5, milk=True))
print(brew("rooibos", milk=True))Parameters with defaults come after the ones without.
Docstrings
A string on the first line of a function is its docstring: what it does, for the people who use it. help() shows it:
def area(width, height):
"""Return the area of a rectangle."""
return width * height
help(area)Tip:The Advanced lesson on names shows one trap with defaults: never use a list or dict as a default value.
More in the Python docs: defining functions, default argument values and docstrings.
Your turn
Write a function tip(bill, percent=10) that returns the tip, rounded to 2 decimal places, and has a docstring. tip(40) should give 4.0 and tip(40, 15) should give 6.0. The last line prints tip(23.5, 20).
Your task
Write a function tip(bill, percent=10) that returns the tip, rounded to 2 decimal places, and has a docstring. tip(40) should give 4.0 and tip(40, 15) should give 6.0. The last line prints tip(23.5, 20).
- tip is defined (not done yet)
- tip(40) returns 4.0 (not done yet)
- tip(40, 15) returns 6.0 (not done yet)
- It has a docstring (not done yet)
- Print tip(23.5, 20) (not done yet)
The checklist ticks itself off as you work in the editor: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
def- Defines a function: def name(parameters): followed by an indented body Python docs →
return- Ends a function and hands a value back to the caller (None if there’s no return) Python docs →
param=default- A default value, used when the caller leaves that argument out. Worked out once, when def runs Python docs →
docstring- A string on a function’s first line that says what it does; help() shows it Python docs →
help()- Shows the documentation of a function, class or module Python docs →