Writing your own custom functions in Python

Basic use cases for using functions in Python

Image for post
Image for post

Functions are a great way for you to make recurrent processes easiser in scripting languages. They make it easy for you to divide codes into useful blocks, readable and time saving. Understanding the basic aesthetics of functions will be a great building block to help you understand how much more complex functions work.

This brief article has been carefully put together, to help you understand how functions work using very basic procedures. By the end of this article, you will understand why you need functions and how to write basic functions.

You can pass data known as parameters into a function and the function can return data as a result. To define/build a function, you use the keyword def:

The function above when run, simply gives the output statement which is My First Function. Let’s build a simple function, that accepts two numbers and returns the addition of such numbers.

The basic function accepts two values, corresponding to the variables a and b which are placeholders as predefined in the function. We will define a simple function that takes in a value, multiplies the value by 5 and returns a result.

Now, let’s do something a bit more advanced. We will define a function that converts temperature in degree Celsius to Fahrenheit.

The actual formula is (F − 32) × 5/9 = 0°C. So the function will have an impute value corresponding to the Fahrenheit scale to be converted to Celsius:

We can go the other way round and build a Celsius to Fahrenheit converter. Using the function (C × 9/5) + 32. Applying the same logic as earlier used for the Fahrenheit to Celsius converter:

Functions can be very simple and become more complex, due to various nesting properties. This is a beginners guide to understanding how functions work in Python. Why don’t you take out time to play around with the little exercise. This will be a multiple part series, as we visit even more complex functions. This is a multiple series article, aimed to graduate you from basic functions to advanced concepts.

Future of Work Africa is a data analytics, consulting, and training company. We provide insights drawn from data to societies, organizations, and individuals make better decisions.

Written by

"The best way to create the future is to create it." This project seeks to prepare professionals for the future through the Application of Data Science and AI.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store