Functions in Python

I recently finished reading John Sonmez's book "Soft Skills". Of particular interest to me was the section on how to learn new things quickly. He lays out a 10-step process. Most of the steps I've already been doing as long as I can remember. But the 10th step - teaching the thing you're trying to learn to others - has been noticeably absent from my process.

So I'm going to start blogging about the things that I'm learning. Since I'm a beginner, these things will be incredibly basic. There might even be some errors from time to time. But John Sonmez makes the point that you only need to be 1 step ahead of someone to teach them. So while someone with any experience might find these articles useless, they could still potentially be of value to someone who is just starting out. I'm committed to learning as fast as I can - thus, I'll be writing these articles both to teach any who might stumble upon them as well as to cement my own knowledge.

Functions in Python

In Python, functions are sections of code that can be "called" and used multiple times throughout your program. They are particularly useful when you know you'll be running the same segment of code multiple times. Instead of writing the code out again and again, you can simply write it once when you define the function, and then call the function wherever you need it.

You can define functions to take arguments. Take the following example:

def add(x, y):
    return x + y

This function takes two parameters, x and y. When you pass in values for x and y, you are passing in arguments. So:

sum = add(5, 7)
print(sum)
>>>12

It's important to note that a function doesn't have to take arguments. Consider:

def say_hi():
    print("Hello!")

Another thing to remember is if you want to extract information from a function, you can set a variable equal to its output, just like we did with the add function up above.

When the function encounters the 'return' command in the code, the function ends, even if there's lines of code below it. You can also simply type 'return' with nothing after it to end the function with no output (although any code above it still would get executed).

If you don't want to write anything into the function for the moment, you can simply write 'pass'. See:

def demo_function():
    pass

And that's it for this super basic lesson on functions. Much more to come!