Define and Call Python Functions
Core idea
A function groups instructions under a name. Write def name(parameter): followed by an indented body. The definition creates a function; calling name(value) runs its body. A parameter is a name in the definition; an argument is a value supplied by the caller. return sends a result back (covered next).
def cost(count): return count * 3
print(cost(4))print(cost(7))The same body calculates two different totals.
Use two parameters
def area(width, height): return width * height
print(area(5, 2))Each argument supplies one parameter.
Define before calling
def announce(): print("Ready")
print("Defined")announce()The body runs only when called here; the definition itself does not print Ready.
Common mistake
Writing announce without parentheses refers to the function, rather than calling it. Keep the body indented and call after the definition has executed.
Practice
Define a function that converts a number of boxes into a count of items at six items per box. Call it for zero and five boxes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Function definition and calls
Check your understanding of defining and calling functions.
What is printed?
def triple(n): return n * 3print(triple(5))What is printed?
def show(): print("Ready")show()What is printed?
def total(a, b): return a + bprint(total(2, 6))Which is a parameter in def scale(value):?