Your First Function

The easiest way to understand or define a function is to say that, it is a mini-program within a program. We have seen functions in the previous chapters, namely print() and input(). Let's create a function to give a better understanding of it. We will make a function to say Hello.

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

sayHello()

If you type this on the white space in your Repl editor and click on Run, the output will be Hello!.

One of the major purposes of a function is to group a block of code that gets executed multiple times. Without a function defined, we will have to print different things with multiple print statements. In general, we always want to avoid duplicating code. Why so? This is because when we update the code, we will have to make a lot of changes, and hence it becomes a tedious task.

Fun Fact: As you get more programming experience, you’ll often find yourself deduplicating code, which means getting rid of duplicated or copy-and-pasted code. Deduplication makes your programs shorter, easier to read, and easier to update.

Now, lets dive deeper into how a function works, and go line by line:

For example purposes, we will write a code to print Hello and a persons name.

def getName(name):
    print("Hello "+ name +"!")

getName("Alan")
getName("Alice")

The resulting output would be:

Hello Alan!
Hello Alice!

As you can see, with a function defined, we just need to pass a new name and voila!

The way to define a function is to use def functionName():. Then, we use a tab space to use that block as the function block. To call the function, we write the function name along with the parameters we wish to pass, such as getName("Alice") in our example.

PRO TIP: Make sure that the function name you choose makes sense with the work of the function. For example, if we named our example function printName(), it would be more easy to understand. Also, use camelCase for naming functions. This is easy to read and a widely adopted practice. Other way to do this would be using_Underscore for this purpose!

results matching ""

    No results matching ""