What is the purpose of using functions in Python?

Today, let’s dive into functions in Python!

“A function is a structuring element in programming languages to group a set of statements so they can be utilized more than once in a program.” (https://www.python-course.eu/python3_functions.php)

We use functions in order to allow for better comprehension and efficiency of the code. Code that is written all over the place with little structure and flow, makes your code very difficult to read. Always remember code will be read far more times than it will be written.

Efficiency is another primary concern when writing code effectively. A rule of thumb is never write the same thing twice. We create functions that essentially perform the role of the copy and paste buttons. As a matter of fact, copy and paste are functions of the programs you use.

Anatomy of a Python function

  • To initialize functions in Python you must preface it with the keyword “def”. This stands for define. You are going to define the function.
  • Following the “def” keyword is a space and the actual function name. Unlike other programming languages, names of functions in Python do not use camel case, instead it uses a combination of lowercase and underscores are used. A good post about naming conventions in Python can be found here and an in-depth introduction to Python styling can be found here, if interested.
  • A function takes parameter(s)/argument(s) which are like car parts going through an assembly line and the function (the workers) puts them together for the desired output (a fully assembled car). These parameters must go in parenthesis with no space in between the function name and themselves. Not every function will have parameter(s).
  • Following the parameters is one singular colon followed by the body of the function. In the body is where the magic happens, this is where the car is put together. A function doesn’t always have an output, sometimes it changes a variable or database item. The function of a function is not always the same.
  • Finally, a function would be worthless without a “call”. You are saying, okay function, I taught you what to do now come do it. Click this link to see an example of a function call. A function call always needs to have parenthesis after it, whether or not the function has parameters.

Comment below if you need any further explanation. Thanks for reading and get coding! Feel free to check out my other Web Development related blog posts here!