Working With Function In Python

in STEMGeeks7 months ago

Welcome back to another instalment of our introduction to programming with Python series we've been presenting over the past few months. In this article we are going to introduce you to Python Functions. We've been using Functions within Python from one of the first articles we presented, for example when we use the print() Function. This is a built in Python Function, and we have been using many of these built in Functions, but we can also create our own Functions to be used within our code and they can also be shared to other users if they needed it.

If you would like to see our previous posts, we have a list in GitHub with our current articles in the README file.

But what are Python Functions and why would we want to create our own? Basically a Function is a block of code that is only run when we ask it to be called. A Function will perform a basic task when called but is created for a number of reasons

  • It allows us to clean up our code as it breaks it up into smaller chunks, making it more organised.
  • Allows us to create reusable code within our programs and like we said earlier, can be provided to other users.

The basic syntax to create a Function within Python is pretty straight forward as you can see from the code below:

def function_name(parameters):
  function code

All Functions in Python need to start with the def keyword as it allows our program to know it is a Function. We then provide a name to the Function, this is what is then called when we wish to use it in our program. The brackets need to be provided, but don't need to include parameters. If parameters are needed to be used as part of our Function, the names of these parameters are included in the brackets. A list of statements and code is then provided in the following indented lines.

Example Python Functions

Sometimes our Function needs to return a value back to the main program. If this is the case, we need to include a return statement as part of our Function creation. Not all functions need to provide a return statement and in the following section, we will provide you with some examples on how to create and use Functions in Python.

If you open up the interactive shell in Python, you can test some of the examples we have below. The first is a basic Function that does nothing. Notice the statements we have after the Function definition only has the work "pass". This needs to be in place as all Functions need to have at least something like this as a statement. Without anything in the body of the Function will cause it to error.

>>> def function_does_nothing():
>>>  pass

>>> function_does_nothing()

We have almost exactly the same thing below where we have another basic Function, this time instead of simply using pass, we have added in a print() statement.

>>> def function_with_no_params():
>>>   print("This function has no parameters")

>>> function_with_no_params()
"This function has no parameters"

The example below shows you how you can use the return statement to return values to main Python program. In example below, instead of using the print() function to output the value from the Function, we are placing that value into a variable and returning the variable back to the main Python program. We then use the print() when calling the Function to output the returned value.

>>> def function_with_no_params():
>>>   value_to_return = "This function has no parameters"
>>>   return value_to_return

>>> print(function_with_no_params())
"This function has no parameters"

The next function below shows how you can use parameters, as we have placed one parameter of "name" in the brackets of the Function definition. This is used by the statement of the Function in the print() function below. When we call the Function in our program, we then include the value in the brackets as we have using the value "Vince". This could also be a variable with the value we need passed to the Function.

>>> def function_with_params(name):
>>>   print("parameters are like variables for the function. they are then specified with the word used in the brackets: {}".format(name))

>>> function_with_params("Vince")
"parameters are like variables for the function. they are then specified with the word used in the brackets: Vince"

If we needed multiple parameters we simply add more separated by a comma.

In the example below, we don't know how many parameters we need, so instead our parameter with a asterisk before as we have with "*kids". This means we can add as many values when calling the Function, which is then passed as a list, but the print() statement could still fail if there is insufficient data provided.

>>> def my_function(*kids):
>>>   print("The youngest child is " + kids[2])

>>> my_function("John", "Mary", "Mark")

You can also send parameters or arguments with the key = value syntax. These are called keyword arguments and this way, the order of the arguments does not matter.

>>> def my_function(name3, name2, name1):
>>>  print(name3)

>>> my_function(name1 = "John", name2 = "Mary", name3 = "Mark")

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

The last example we have below is where we include a default parameter, so a parameter is not actually needed when the Function is called by the program.

>>> def my_default_params(country = "Norway"):
>>>   print(country)

>>> my_default_params()

NOTE: Functions need to be in the program before they are called. This means we usually include a space at the start of the program to include all of the Functions, before the main body of the program is created.

Creating Functions Inside Our Python Program

If we then separate the work we are doing in our program we have been working on, we would be able to create two functions at the start of our program. one called check_savings() and the second called add_savings().

You'll notice we have the amount parameter included as part of the add_savings() function.

The code can be found at the following link

NOTE: As always the line numbers are listed to help explain the code and should not be included when entering the code.

As you can see we have added the functions to the start of our program with check_savings() at line 4, which simple opens our text file and prints out the total of savings at line 14. We then have the add_savings() function at line 16, which the amount parameter to be include, which is then added to our text file. You will then notice line 20 then calls the check_savings() Function from within add_savings(), which is completely fine to do as long as check_savings() has been created previously in the program.

   1 #!/usr/bin/env python
   3 # Set up the functions our program will use
   4 def check_savings():
   5   total = 0
   6   f = open("savings.txt", "r")
   7   savings_from_file = f.readlines()
   8   f.close()
 11  for i in savings_from_file:
 12     total += int(i)
 14  print("\nI have saved ${} so far this year\n".format(total))
 16 def add_savings(amount):
 17   f = open("savings.txt","a")
 18   f.write("\n{}".format(amount))
 19   f.close()
 20   check_savings()

We then complete the rest of the code that looks pretty similar to our previous code. We have the menu presented to the user asking the user to make a selection. This selection is then tested and either add_savings() at line 37 is then called by the main body of the program to add savings, or check_savings() is called in line 39. You'll notice the add_savings() function also includes the "savings" variable as a parameter when the Function is called.

 22 # Welcome the user and provide a menu
 23 while True:
 24   print("Welcome to Python Savings.")
 25   print("Choose from one of the tasks below.")
 26   print("1. Add Savings.")
 27   print("2. View Savings.")
 28   print("3. Quit Program.")
 30    choice = input("From the items above make a select from 1 - 3: ")
 32   if (int(choice) == 3):
 33     break
 34   elif (int(choice) < 3):
 35     if (int(choice) == 1):
 36       savings = input("\nHow much money did you save today? ")
 37       add_savings(savings)
 38     else:
 39       check_savings()
 40   else:
 41     print("\nYou have made an invalid choice, please try again\n")

When we run the program, hopefully you should see something similar to what we have below. We have been using a savings.txt file that already has items added.

python .\
Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 1

How much money did you save today? 

I have saved $1100 so far this year

Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 6

You have made an invalid choice, please try again

Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 3

We've made our program a little nicer, but we can make it even more readable and user friendly but turning our functions into an external module and importing this into our Python program. But for now we've run out of time and we will pick this up in our next article. For now though we have covered a lot of work on Functions and hope you have learnt something from the article.

Posted with STEMGeeks