How to use functions in Python

What are functions?

Functions are like containers that we can store some code inside so that we can reuse it whenver or wherever we like to use it inside our code. I will be using python to explain function in this blog post.

Let's I want to write a program to print my name in python, I could do it this way.

print("My name is Joseph")

Any time I want to print my name inside my program, I would have to be typing the full code. This is a rather stressful way to write code because I would have to repeat myself every time I need the code. Example: if I want to print my name 5 times, I would have to write something like this.

print("My name is Joseph")
print("My name is Joseph")
print("My name is Joseph")
print("My name is Joseph")
print("My name is Joseph")

As you can see it is very stressful. It will waste my time if I try to copy and paste, and it will also waste the computer's memory. In programming, there is this rule called DRY. It means that you should not repeat yourself.

It is not proper as a programmer to copy and paste code. Anytime you copy and paste code, it is more likely that you are writing a bad code

What if I could store that code somewhere so that I don't have to always repeat myself? It is possible to do that. Here is what it would look like:

# this is how to write a function
def print_my_name():
    print("My name is Joseph")

Any time I need to print my name, all I need to do is to call the function.

So how do I call a function?

Just write the name of the function and then, add parenthesis in front where ever you need it.

Like this:

print_my_name()

How to create a function.

You create a function in python by using the keyword,

def

followed by the name of the function, followed by a parenthesis then you add a column in front. You are to then indent the next line four (4) spaces like this. All the code that you want to be inside a function should be indented by four spaces.

If I want to print two lines of information about myself, it would be like this.

def my_information():
    print("My name is Joseph")
    print("I love to program")

How to use a function.

All I need to use the function I created is to type the name and add parenthesis in front.

my_information()

You can go ahead to create some functions. You can write a function to add two numbers, do complex things and just about anything you want to do.

So that's how to create and use functions. There are still more things to functions, but I will be explaining them in future posts.