Chapter 10: Organizing Your Code with Functions
As your programs have grown, you've probably noticed that you sometimes write the same or similar lines of code in multiple places. If you need to make a change, you have to find and update every single copy. This can be tedious and is a common source of bugs.
The solution is to organize your code into reusable blocks called functions.
What is a Function?
You can think of a function as a named mini-program inside your main program. It's a block of code designed to perform one specific task. Whenever you need to perform that task, you just "call" the function by its name instead of re-typing all the code.
You've already used some built-in functions, like print(), len(), and range(). Now, you'll learn how to create your own.
The core principle behind functions is DRY: Don't Repeat Yourself.
Defining and Calling a Function
You create a function using the def keyword, followed by the function's name, a set of parentheses (), and a colon :. The code that belongs to the function is indented below the def line.
Let's create a simple function to say hello.
# 1. Defining the function
def greet_user():
"""This is a docstring. It explains what the function does."""
print("Hello!")
print("Welcome to the world of Python functions.")
# 2. Calling the function
print("The program starts here.")
greet_user()
print("The program has finished.")
Output:
There are two parts:
Defining: The
def greet_user():block creates the function and tells Python what it should do when it's run. The code inside doesn't execute immediately.Calling:
greet_user()is the line that actually runs the code inside the function.
The text inside the triple quotes """...""" is called a docstring. It's a special type of comment that explains the function's purpose. It's a very good habit to include a docstring for every function you write.
Passing Information to a Function (Parameters)
Functions become much more useful when you can pass information to them. You can make your greet_user function more personal by allowing it to greet a specific person.
You do this by adding parameters inside the parentheses when you define the function. A parameter is a variable that acts as a placeholder for the information you want to pass in.
Output:
Parameter:
namein the function definition (def greet_user_by_name(name):).Argument:
"Alice"is the value (the argument) you pass to the function when you call it. This value gets assigned to thenameparameter inside the function.
You can have multiple parameters, separated by commas:
Getting a Value Back (The return Statement)
return Statement)So far, our functions have only done something (they've printed text). But what if you want a function to calculate a value and give it back to you, so you can store it in a variable and use it later?
For this, we use the return statement. When Python sees return, it exits the function immediately and sends the specified value back to where the function was called.
Let's rewrite our add_numbers function to be more useful.
Output:
By using return, we can now use the function's output in other parts of our program. This is much more flexible than just printing the result.
Summary and What's Next
Functions are the building blocks of larger, well-organized programs.
You define a function with
def.You call a function to execute its code.
Parameters are placeholders for data in the function's definition.
Arguments are the actual values you pass to a function when you call it.
The
returnstatement sends a value back from a function.
You've now covered the most essential programming fundamentals in Python! You understand variables, data types, operators, control flow (if/else), loops, data structures, and now functions.
In the next chapter, we'll put all of this together to build our very first complete project: a fun number guessing game.
Practice Time!
Write a function called
show_favorite_moviethat takes one parameter,movie_title, and prints a message like "My favorite movie is [Movie Title]".Write a function called
calculate_areathat takes two parameters,widthandheight, andreturns the area (width * height).Call your
calculate_areafunction with numbers of your choice and store the result in a variable calledrectangle_area. Print the value of that variable.
Last updated