Press enter to skip the top menu

Python Programming

Functions

NCEA Compatibility

Module: as91883 Develop a computer program

Requirements: User-defined methods, functions or procedures

Go to top

Learing Outcomes

On completion of this section you will be familiar with

Go to top

Introduction

Listing 1 below is a reprint of one of the first programmes we wrote. It is a very simple programme that is very easy to follow since the individual lines of the input, processing and output followed each other in a very logical sequence from top to bottom. There is hardly any need for comments or documentation due to its simplicity.

Listing 1
                    
                        #C2Interactive Payroll Programme
                        strName=input("Enter employee's full name:  ")
                        floatHours=float(input("Enter value for hours:  "))
                        floatRate=float(input("Enter value for rate:  "))
                        floatGross=floatHours * floatRate
                        floatTax=floatGross * 0.25
                        floatNet=floatGross-floatTax
                        print("Gross is " + str(floatGross))
                        print("Tax is " + str(floatTax))
                        print("Net is " + str(floatNet))
                    
                    

Of course this programme was so simple that it was of no use in real life. In order to make it more useful we added an if..else construct in order to calculate the tax. After that we added a if..else..elif construct in order to calculate the superannuation. Finally, in order to validate the hours and rate we added two while loops, one for each value.

Recall that the if.. else construct was added to handle the complexity of the tax calculation, the if..elif..else to handle the even more complex superannuation contribution and the while loop to handle the validation of the data going into the variable floatHours. Adding these extra functionalities added to the complexity of the programme and made it difficult to read and interpret.

Our aim here is to restore the original simplicity of the programme. To do this we shall separate the processing from the main programme so that the main programme will retain the simplicity of Listing 1 above. The processing we are separating include the calculation of the gross, the tax, the superannuation and the net. Those are three separate processings which we shall divide up among four separate functions which we shall name calculateGross, calculateTax() and calculateNet(). We shall also create another function that will display the calculated values for the gross, tax, superannuation contribution and the net pay. We shall call this function showData().

As well as making our programme easier to read, functions have another benefit. Suppose that there was a group of lines of programme code that were required to be used in different parts of the programme, we can simply write out the lines of code separately for each part of the programme where they are required. This has two drawbacks:

The other alternative is to write the group of lines together only once and then to call that group whenever we need to use them. This has the following advantages:

Go to top

How to create a Function

Listing 2
                    
                        def calculateTax(gross):
                            if gross < 500:
                                tax=gross * 0.25
                            else:
                                tax=125 + (gross-500) * 0.33
                            return tax
                    

Listing 2 above shows how a function is created.

In line 1 the function is defined using the keyword def. This is followed by the name of the function – calculateTax(), in this case. The name of the function is followed by and opening and closing bracket and between those you can have as many parameters as you wish.

What is a parameter? A parameter is a variable that holds a value that has been passed to the function by the main programme, or by another function. In our case, once our programme has calculated the value of the gross, it calls the function calculateTax() and passes the value of the gross to it. This value will be stored in the parameter gross.

To finish off the description of the first line of code we must point out the colon at the end of the line. This colon specifies that lines 2 to 6 are subservient to line 1 or, in other words, are the body of the function.

Lines 2 to 5 consist of an if..else construct. This construct tests the value of the parameter and if it is less than 500 the value of the local variable tax is calculated in line 3, otherwise the value of tax is calculated at line5.

Line 6 has something new for us – the keyword return. In our case this is followed by the variable tax. Before describing this keyword we must first look at the concept of local variables.

The variable tax has been created inside the function calculateGross() and is therefore only visible inside the body of the function. This type of a variable is referred to as a local variable.

Since the variable tax is local to the function calculateGross() it cannot be seen by the main programme and if we need to get the value stored variable back to the main programme we have to use the keyword return to do so.

Once we start examining the main programme we shall show you exactly how this is done.

Go to top

Extending the Payroll

Listing 3
                        #CC8 Functions.py
                        #function for calculating gross
                        def calculateGross(hours, rate):
                            gross=hours*rate
                            return gross
                        
                        #function for calculating tax
                        def calculateTax(gross):
                            if gross < 500:
                        	    tax=gross * 0.25
                            else:
                        	    tax=125 + (gross-500) * 0.33
                            return tax
                        
                        #function for calculating the net
                        def calculateNet(gross, tax):
                            net=gross - tax
                            return net
                        	
                        #function for displaying results
                        def showData(gross, tax, net):
                            print("Gross:    " + str(gross))
                            print("Tax:      " + str(tax))
                            print("Net:      " + str(net))	
                        	
                        #Main body of programme
                        
                        #input section
                        strName = input("Enter employee's full name:  ")
                        floatHours = float(input("Enter value for hours:  "))
                        floatRate = float(input("Enter value for rate:  "))
                        
                        #processing section
                        floatGross = calculateGross(floatHours, floatRate)
                        floatTax = calculateTax(floatGross)
                        floatNet = calculateNet(floatGross,floatTax)
                        
                        #output section
                        showData(floatGross,floatTax,floatNet)
                   
                    

In Listing 3 above lines 1 to 24 is the area where the programme’s functions are stored. Even though the code for the functions is at the start of the programme the same functions are not executed immediately. This is because the first line of each function defines it to be a function and Python will not run functions unless they are called from somewhere else. For this reason we have to get down as far as line 29 before we meet the first line that will be executed. This line and the two that follow it allow the user to enter values for the employee’s name, the hours worked and the hourly rate. These lines have not changed since the previous version of the programme and therefore there is no need to discuss them.

The processing section spans lines 34 to 36. In order to explain it let us assume that the user entered 20 and 30 for the hours and the rate and that therefore these values are stored in the variables floatHours and floatRate .

At line 34 the function calculateGross(floatHours, floatRate) is called This means that control will pass up to line 3 and the values 20 and 30 that were stored in the variables floatHours and floatRate are copied into the parameters hours and rate at line 3.

Once this copying is done, execution of the function begins at line 4. Here the values of hours and rate, i.e. 20 and 30, are multiplied and the result stored in the local variable gross. Thus the variable gross has 600 stored in it.

We must get this value back to the main programme. This occurs at line 5 with the code return gross. This causes programme control to return back to line 34 and to carry the value of the local variable gross with it. On returning to line 34 the value of gross, i.e. 600 is stored in the variable floatGross.

At line 35 the function calculateTax(floatGross) is called. This causes programme control to pass to line 8 and also causes the value stored in the variable floatGross, i.e. 600 to be copied to the parameter gross.

Once execution starts the condition at line 9 will be false since 600 is not less than 500 and therefore control will pass to line 12 where tax is calculated as 125 + (600-500) * 0.33 = 125 + 33 = 158.

Line 13 returns this value back to the variable floatTax in line 35.

Once line 35 completes processing, programme control passes to line 36 where the value of the net is calculated

The value of the net is calculated at line 36. This is done by subtraccting the tax from the gross. To do this the function calculateNet(floatGross, floatTax) is called and thus control passes to line 16, where the values 600, 158 and 60 are copied into the parameters gross and tax .

At line 17 the value of the net is calculated as 600 – 158 = 442, which is then stored in the local variable net.

At lien 18 the keyword return returns the programme control and this value back to line 36 where it is stored in the variable floatNet.

By now the processing is complete and control passes to line 39 which is the first and only line of the output section. Here the function showData(floatGross, floatTax, floatNet) is called. Control passes to line 21 where the values 600, 158 and 422 are copied into the variables gross, tax and net. Lines 22 to 24 display those values along with the appropriate labels.

Notice that there is no return keyword in function showData(). This is because the function does not perform any calculations and that its sole purpose is to present the calculated data to the user. A sample output containing the values discussed here is shown in Fig 1 below.

Fig 1

Before finishing this section let us take a look at the main body of the programme, i.e. lines 46 to 59. We have managed to restore the original simplicity of our original programme:

Go to top

Functions for validating Input Data

Listing 4
                    
                        #CC8 Functions.py
                        
                        #function for validating a floating point number
                        def validateFloat(base, top, prompt):
                            floatValue=float(input(prompt))
                            while (floatValue < float(base) or floatValue > float(top)):
                                print("Value must be in the range "+str(base) + " to " +str(top))
                                floatValue=float(input(prompt))
                            return floatValue
                        
                        #function for validating an integer
                        def validateInt(base, top, prompt):
                            intValue=int(input(prompt))
                            while (intValue < int(base) or intValue > int(top)):
                                print("Value must be in the range "+str(base) + " to " +str(top))
                                intValue=int(input(prompt))
                            return intValue
                    

Listing 4 above shows two functions for validating input data. Both functions are identical in structure and logic. The only difference between them is that the first one validates floating point numbers while the second one validates integers. They could be added to the code in Listing 3 so that the hours and hourly rate could be validated as being within allowed ranges. An example of a call to one of the functions could be:

floatHours = validateFloat(5, 60, “Enter value for hours worked”)

In this case programme control would pass to line 4 of Listing 4 where the values 5, 60 and “Enter values for hours worked” are copied into the parameters base, top and prompt.

Line 5 simply prompts the user to enter a value. The prompt would appear as follows on the console:

Enter value for hours worked :

This value entered by the user will then be stored in the local variable floatValue.

Line 6, the control line of the while loop tests the new value for being less than the parameter base or greater than the parameter top, or, in our case, being less than 5 or greater than 60. If either of those conditions is true then the body of the loop is entered.

At line 7 an error message is created by adding together the text item “Values must be in the range ”, a string version of the parameter base, the text item “ to ” and a string version of the parameter top. In our case the error message would be:

Value must be in the range 5 to 60

A line 8 the user is again prompted to enter another value and then programme control passes back to line 6.

As with all example, of the while loop this process repeats itself until the user enters a value within the range base to top or 5 – 60 in our case.

Go to top

Practice

Copy Listing 3 into a .py file and run it. Check that it is working satisfactorily.

Once this is running to your satisfaction copy the code in Listing 4 and paste it into the same .py file. It does not matter where in the .py file you paste this code as long as it is not in the middle of the programme body or in the middle of another function. Now alter the line for inputting the value of hours as follows:

floatHours = validateFloat(5, 60, “Enter value for hours worked”)

Alter the line for inputting the rate in the same manner.

Once the code is running satisfactorily experiment with different lower and upper values for hours and rate and check that the altered programme applies those new limits.

Go to top

Exercise

  1. How does the use of functions lead to having better written programmes?
  2. What does an parameters mean as far as functions are concerned?
  3. What co-relation must exist between the parameters and the data passed to them?
  4. Describe in detail the similarities and differences between functions and procedures

Go to top

Summary

Functions are used to simplify the main body of a program. They do this as follows:

  • The complex processing from the main program and saving the processing block using a descriptive name.
  • The space where the processing block was, is filled only with the name of the function.
  • Once all of the processing blocks are replaced by their names, the main body of the program is easier to follow

Functions make programming more efficient

If the same processing is required in multiple parts of the program it is more efficient to put the processing into a function and then call the function from whichever parts of the program it is required.

This has a number of benefits:

  • reduced the size of the program
  • avoids multiple rewrites of the same code, thus saving time
  • makes updating the program easier as one needs to update the single function and not the numtiple versions of it
  • reduces inconsistency that may occur with multiple copies of the same code
Go to top

Assignment

Modify the code you have created for Assignment Part 5 as follows:

  1. Put the calculation of the subtotal, GST, discount and total into three separate functions called calculateSubtotal, calculateGST, calculateDiscount, calculateTotal.
  2. The function calculateSubtotal will have two arguments, the unit price and the amount sold.
  3. The function calculateGST will have only one argument: the subtotal
  4. The function caculateDiscount will have two arguments: the subtotal and the discount code
  5. The function calculateTotal will have three arguments: the subtotal, the GSt and the discount
  6. There must also be a function for printing the data called showData. This will print out the values of subtotal, GST, discount and total.

Although a major reorganization of the programme has occurred here there has been no change in the actual processing. The test data for this part will be exactly the same as that for Part 5.

Go to top