Defining and Invoking Custom Python Functions
In this lesson, you will learn how to organize your code into reusable "mini-programs" called functions, allowing you to write logic once and execute it whenever you need it.
Up until now, you have likely been writing your code in one long sequence. While this works, it often leads to repetitive code. Instead of copying and pasting the same logic, you can use the def keyword to "package" that logic into a function. Think of a function like a recipe: you write the steps down once, and then you can "cook" (invoke) that recipe as many times as you want.
How to Define and Invoke
To create a function, you start with the def keyword, followed by the function name, parentheses (), and a colon :. Everything indented beneath it is the "body" of the function. To run that code, you simply type the name of the function followed by parentheses.
# Defining the function
def greet_user():
print("Hello! Welcome to your custom program.")
# Invoking (calling) the function
greet_user()
greet_user()
When you define greet_user, Python stores the code block but does not run it yet. When you write greet_user() on a new line, you are telling Python to jump into the function, execute the print statement, and then return to where it left off.
Why This Matters
By breaking your program into smaller, named functions, you make your code much easier to read and maintain. If you need to change the greeting, you only have to edit it in one place (inside the def block) rather than hunting through your entire script to find every instance where you printed a message. This encapsulation keeps your program organized and prevents the "spaghetti code" that often happens when everything is written in one giant, flat file.
Key Takeaway: Use the def keyword to define a function to store a reusable block of code, and execute it by calling its name followed by parentheses.