Making Your Own Python Functions!

Updated 14 April 2022

Progressing further into the epic programming language of Python the instinctive next step should be user defined functions. Now as a quick refresher, a function in Python is a block of code which only runs when it is called. It is organised, reusable and performs a single related action. Functions are all about making it easier for the Pythonista whilst increasing both the modularity and reusability of the code. Leading from that, a user defined function is a programmed routine that has parameters set by the user of the system. Simply, a user defined function would be a Python script, that you have created, which can be called upon and run by different programs. 

User defined functions can seem very different for new programmers, particularly in the way they are called into action, but understand that they are there to enable the best potential out of the Python programming language. The contents of this tutorial with quick links can be seen below.

A great place to start your journey would be Python Rundown and Main Windows. This guide will also tell you where to download Python and access online Python emulators. Python is an excellent language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB. These are computing devices that can easily fit on the palm of your hand.

Let's learn how to make our own FUNctions! As always if you have any questions, queries or things to add please let us know your thoughts!


Syntax For Creating a Function

A fun looking tube galA function is a reusable block of programming statements designed to perform a certain task. The keyword | def | is the method Python uses to create user-defined functions. All user defined functions begin with a def statement followed by the function name. Let me give you a guide example of the syntax to produce a user created function which also uses the | return | keyword.
 

def  Name ( Parameters 1, Parameter 2, Parameter 3):
                Block of Code
                return 

 
The block of code usually incorporates parameter information. Coded into the calling environment will be the name of the function desired and the necessary information to fill out the parameters. The calling environment can also be referred to as the caller program. Parameters are information that is passed onto the function. These can also be referred to as arguments. You can add as many parameters as you want just separate them with a comma. Crucially the same number of actual arguments must be provided as those asked for by the function.

It is worth noting every function in Python returns something back to the calling environment. If no return statement exists in the code of the function then it will return | None |. More on this keyword can be found at the guide All the Keywords in Python! Also a function can return multiple types of values and it can do so using a single return statement. 


Return Statement

Old School Tube BoiThere is a lot going on with the | return | keyword within Python. So below is a list to clarify what, where and how to use it.

- This keyword can be used inside a function only!
- This keyword will terminate the function execution.
- The return statement is used in the function to return something (example would be a numeric value) to the calling environment. 
- Every function in Python returns something, if there are no return statement it will return | None | to the calling environment.
- Multiple return statements can be utilised within a function but as soon as any are executed the function terminates.
- When there is an expression (ergo a mathematical calculation) inside a return statement the expression evaluates first.


User Created Function Examples

The following will be a series of functions created in the Python Programming Window which are called upon by the Python IDLE Shell. In these examples the Python IDLE Shell is utilised as the calling environment. Once the function executes it will then print out the result to the Python IDLE Shell.  

1. Below is a repeating function that will echo back whatever you have typed as the parameter (still has me checking over my shoulder though). The function has been given the name Repeat and when it executes it prints whatever parameters are given to the calling environment straight away. 

A Repeating function that will say back whatever you say. Still has me checking over my shoulder though.

 

2. Below is a function that will perform an average of the five parameters given. The addition is done inside the function and the division is done inside the print function. The print function produces integer, string and float values to the calling environment. Neat.

A function that will perform an averaging of the 5 values given. Neat.

 

3. Below is a calculator that is programmed to print a series of calculations on five different parameters. It has been given the name Simple_Calculations. It demonstrates that multiple print functions can be used inside a print function. It will display the results to the calling environment.

A calculator that is programmed to print a series of calculations on 5 parameters.

 

4. Below is a function that will offer a greeting and then give a statement about the weather. This demonstrates the potential of functions. Imagine there were lots of people to say hello to and tell what the weather was. Those people could be in a list (or excel sheet, get to that later) and the user created Python function would be able to run through and give everyone a personalised greeting message. This would save so much more time than manually doing this. Furthermore, imagine if the Python function would access information on the persons location and the weather for that day. Then this system could be completed automated. Below is a simplification of this as this guide is an introduction. Below also shows different ways to get parameters and strings to be printed together to the calling environment.

Hello World this is the Weather today. Hopefully you can see the potential of functions emerging now, particularly if there are lots of people to say hello this is the weather to.

 

5. Below is a script which emulates a timer for a rocket to blast off. The timer starting point is based on the parameter you give it to start. A while loop is incorporated into the function as well. Indentation is increased a further step for all code inside the loop body. Worth noting, nested loops can work perfectly fine inside user created functions it just requires further steps of indentation. The results will be printed to the calling environment.

Loops and all other keywords will work just fine inside functions. You can even use nested operations with no issues.


The Next Step

Scope would be the best next avenue to explore within Python. The guide Scope in Python is exactly the place to learn just this. This will inform you just how variables, objects and other namespaces can be linked and interacted with when using your own created functions.


DOWNLOAD THE CODES

Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open it up with Python IDLE Shell and run it using the Python Programming Window.

Attachment - Python-Make-Your-Own-Functions-Examples.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.