Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is def in Python

Understanding the Basics of Functions in Python

When you're starting to learn programming, it's like learning a new language. Just like in any language, there are verbs that signify actions. In Python, one of the key 'verbs' you'll encounter is def. This short, simple word stands for 'define' and it's how you tell Python that you're about to create a function, which is a reusable block of code designed to perform a specific task.

What is a Function?

Imagine you have a recipe for making a sandwich. Every time you're hungry, you don't need to go through the recipe from scratch. You just remember 'make a sandwich' and your brain automatically knows the steps involved. In programming, a function is like that mental recipe. It's a set of instructions that you can use over and over again without having to rewrite the steps each time.

The Role of def in Python

In Python, to create this recipe or function, you use the keyword def. This tells Python, "Hey, I'm about to give you a set of instructions that I want to use again later." After def, you give your function a name, followed by parentheses which can hold ingredients, known as parameters, and then a colon. Here's a simple example:

def say_hello():
    print("Hello, world!")

In this case, say_hello is the name of our function, and it contains one instruction: print("Hello, world!"). There are no parameters in the parentheses, meaning this function doesn't need any extra information to do its job.

Parameters: Giving Information to Functions

But what if your recipe needs some specific information? Like who you're making the sandwich for? Parameters are like placeholders for this information. When you call, or use, the function, you can pass in these details.

def greet_person(name):
    print(f"Hello, {name}!")

Here, name is a parameter. When you use greet_person, you need to provide a name so that the function can include it in the greeting.

Calling a Function

Creating a function doesn't make it run by itself. You need to call it, just like shouting "Dinner's ready!" to make everyone come to the table. Here's how you call the greet_person function:

greet_person("Alice")

When you run this line of code, you'll see Hello, Alice! printed out.

Return Values: Getting Results from Functions

Sometimes, you want your function to give you something back. For instance, if you had a function to add two numbers, you'd want to know the result. This is where return comes into play.

def add_numbers(a, b):
    return a + b

The return keyword tells Python, "This is the result I want to send back." If you call add_numbers(3, 4), it will give you 7.

Why Use Functions?

Functions help you avoid repeating code, making your programs shorter and easier to read. If you find yourself writing the same code multiple times, it's a sign you might need a function.

Nesting Functions: Functions Inside Functions

Just like you can have a small task within a larger recipe, you can have functions inside other functions. This is called nesting.

def make_sandwich(bread, filling):
    def prepare_ingredients(ingredient):
        print(f"Adding {ingredient}...")
    prepare_ingredients(bread)
    prepare_ingredients(filling)
    print("Sandwich is ready!")

make_sandwich("Rye bread", "Cheese")

Here, prepare_ingredients is a nested function that's only used within make_sandwich.

Scope: Keeping Secrets Between Functions

In programming, not all information is shared everywhere. The concept of scope determines where a piece of information is available. If you define a variable inside a function, it's like a secret kept within that function. It's not known to the outside world.

def my_secret_function():
    secret = "I love Python!"
    print(secret)

my_secret_function()
# print(secret) # This would cause an error because 'secret' is not known outside the function.

Default Parameters: Providing Default Values

Sometimes, you want your function to have a default value, like a default sandwich order. You can set default parameters for this purpose.

def make_coffee(type="Espresso"):
    print(f"Making a cup of {type}.")

make_coffee() # Makes an Espresso, which is the default type
make_coffee("Latte") # Makes a Latte instead

Conclusion: The Power of def

As you journey through the world of programming, def will be one of your trusty companions. It's the gateway to creating your own functions, which are the building blocks of Python programs. They help you write cleaner, more efficient code, and once you get the hang of them, you'll start seeing opportunities to use functions everywhere.

Think of def as the spell that conjures functions into existence, giving you the power to tell your program to do exactly what you want. With each function you define, you're not just writing code; you're crafting a toolkit that you can reach into whenever you face a problem that needs solving. So go ahead, define away, and watch as your lines of code transform into a symphony of well-organized, reusable pieces of logic that make up the magic of programming.