← Intro to programming with Python
Making your own functions
Name a group of steps and run it whenever you like.
You have been USING functions all along: print(), len(), input(). Now you can make your own. def gives a name to a group of steps, and calling that name runs them. Parameters are the blanks the function fills in each time, like the name on a birthday card. Why bother? Write the steps once, use them many times, and fix a bug in one place instead of ten.
def greet(name):
print(f"Hello, {name}! Welcome aboard.")
greet("Aisha")
greet("Diego")def greet(name): defines the function; nothing happens yet. Each call, greet("Aisha"), runs the indented lines with name set to that value.
Common mistake: defining a function but never calling it. A def on its own only creates the tool; you have to write greet("...") to use it.
Another common mistake: calling the function ABOVE its def. Python reads top to bottom, so the def must come first.
A function can take several parameters, separated by commas: def area(width, height):. The values in the call are matched up in order.