Functions

Functions

For the final article in “the Basics of Python,” we will go over Python Functions. This is a simple skill to learn as an experienced programmer, but regardless of your coding experience, you will certainly come across functions in your programs.

If you are new to computer coding, functions are used many times for organizing your code into chunks and making it easier on yourself. Functions essentially help you group code together that you can use in different parts of a program without rewriting this code.

Syntax

The basic syntax of a Python function looks like this:

As you can imagine, upon calling this function, (calling means to run the function which I will explain later on), it will returns (or give back) the answer 12. The parenthesis next to the name of the function is not optional and is there to hold your parameters. One way to think of parameters is as variables to use inside the function. For example, if there is a dynamic value you need to use in your program, you will set it as a parameter, then set the value of the parameter upon calling the function. For example:

Here, x and y aren’t given a value, and instead, we will define them when we call the function.

Calling a function

The above image is an example of how to call a function. In this case, we are printing the result of the function with the name and parenthesis next to it. If we have any parameters in the function, we need to define them here like so:

I hope this tutorial helped you understand Python Functions. If you have any questions, feel free to leave them in the comments section below!

Close Bitnami banner
Bitnami