No history yet

Function Basics

Creating Reusable Code

Imagine you have a task you need to do over and over, like making a sandwich. You wouldn't re-learn the steps every single time. Instead, you'd have a mental recipe: get bread, add filling, put slices together. In programming, we have a similar concept called a function.

A function is a reusable block of code that performs a specific task. It's like a mini-program within your main program.

Using functions helps keep your code organized and easy to read. More importantly, it follows the "Don't Repeat Yourself" (DRY) principle. If you need to perform the same action multiple times, you just write the code once inside a function and then call that function whenever you need it. If you ever need to change how the task is done, you only have to update it in one place.

Defining and Calling Functions

To create a function in Python, you use the def keyword, which stands for "define." You give your function a name, followed by parentheses () and a colon :.

The code that belongs to the function goes on the next lines and must be indented. This indentation is crucial; it's how Python knows which lines of code are part of the function.

def greet_user():
    # This code is inside the function
    print("Hello there!")
    print("Welcome to the program.")

Defining a function doesn't run the code inside it. It just tells Python that this block of code exists and what its name is. To actually run the code, you need to call the function. You do this by writing the function's name followed by parentheses.

# This defines the function
def greet_user():
    print("Hello there!")
    print("Welcome to the program.")

# This calls the function, running the code inside
greet_user()

# You can call it again!
greet_user()

When you run this script, the print statements inside greet_user will execute twice, once for each time the function is called. The output would look like this:

Hello there! Welcome to the program. Hello there! Welcome to the program.

By packaging our greeting into a function, we can easily reuse it without rewriting the print statements.

Now, let's test your understanding of these core concepts.

Quiz Questions 1/5

What is the main benefit of using functions in programming?

Quiz Questions 2/5

To create a function in Python, you use the ______ keyword, followed by the function name, parentheses, and a colon.

Functions are a fundamental building block in Python that you'll use constantly to structure your programs.