Press enter to skip the top menu

Python Programming

Decisions

NCEA Compatibility

Module: as91883 Develop a computer program

Requirements:Selection

Go to top

Learning Outcomes

On completion of this section you shall know:

Go to top

Introduction

In all aspects of life we make decisions. Examples are if the buses are running we shall go into town, otherwise we shall study. In programming we have to make decisions as well or to be more precise we shall tell the computer how to make decisions. To demonstrate this we shall modify the programme created in the previous chapter so tax is calculated in a different way. In the previous example we had a simple flat tax rate of 25%. In real life tax rates are never as simple as this. If the salary is low then the tax rate will also be low but a higher salary will incur higher tax rate. In our case we shall modify the simple payroll programme we met in the previous lesson so that it will calculate tax in two different ways depending on the value of the gross pay.

Go to top

A Simple Decision

for our first example we shall look at a very simple exmple of decision makeing - the simplest if statement. This is shown in Listing 1 below.

Listing 1
                        #C2A Simple Payroll Programme
                        strDecision=input("Do you want to run payroll?  ")
                        if strDecision=="Yes":
                            floatHours=20.0
                            floatRate=15.0
                            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))
                    

At first glance we see that most of the code is a repeat of that from the previous page. We notice, however, that a major change has occurred in the structure of the code.

There are two major changes:

What's this all about?

Line 3 is a condition. There are three indications to this:

All of line 3 could be translated into normal English as follows: if the text entered by the user into the variable strDecision at line 2 is the word "Yes"

Similarly we can interpret the indented lines 4 - 11 as: these lines will be executed if and only if the value stored in the variable strDecision is the word "Yes".

Another conclusion we can draw from this is that if the value stored in strDecision is NOT "Yes" then lines 4 - 11 are ignored. This would mean that only lines 2 and 3 would be executed and the rest would be ignored. This is shown in Fig 1 below.

Fig 1
Go to top

A more realistic Decision

In in the lesson ‘A simple Python Programme’ tax was calculated as a flat 25% of the gross. As stated above tax calculation is not quite this simple. Most governments have different levels of taxation depending on a person’s income level. In our case we shall assume that any gross which is $500 or less will be taxed at 25% whereas any gross that exceeds $500 will be taxed at 25% of the first $500 and 33% of the remainder.

The above scenario leaves us with a two way system for calculating tax: one way for gross less than 500 and another for gross greater than 500. Our simple example in Listing will not work in this case as it can allow for only a condition having a value of true. It has no ability to deal with the case of the condition being false. For this we need an extension of the if construt. This extension is the if..else construct.

Listing 2 shows how this construct works.

Listing 2
                    
                        #C3Payroll Programme Decisions.py
                        strName=input("Enter employee's full name:  ")
                        floatHours=float(input("Enter value for hours:  "))
                        floatRate=float(input("Enter value for rate:  "))
                        floatGross=floatHours * floatRate
                        if floatGross<500:
                            floatTax=floatGross * 0.25
                        else:
                            floatTax=125+(floatGross - 500) * 0.33
                        floatNet=floatGross-floatTax
                        print("Gross is " + str(floatGross))
                        print("Tax is " + str(floatTax))
                        print("Net is " + str(floatNet))
                    
                    

Apart from lines 6 to 9, the programme shown in Listing 2 is identical to the programme we met in the lesson ‘A simple Python Programme’. We shall therefore concentrate solely on this group of lines.

As stated earlier we need a programme that can make a decision between calculating the tax in one of two different ways. The main decision point is at line 6. Here we have the keyword if followed by the condition floatGross<500.

A condition, of course, can be either true or false. If the variable floatGross has a value of 400 then the condition is true, whereas if it has a value of 600 then the condition is false.

How does Python work with these conditions? At line 6 if floatGross has a value of 400 then the condition is true, since 400 is less than 500. In this case programme control passes to the body of the if, or in other words to line 7.

Notice that line 7 is indented by four spaces. As we stated earlier this means that this line will only be executed if the condition at line 6 is true. Thus if the value of floatGross is 400 then line 7 will be executed and a value of 100 will be stored in floatTax. Then control is passed to line 8.

Here the keyword else means that the indented lines that follow it will only be executed if the condition at line 6 is false. Following our example of floatGross having a value of 400 then line 7 would have been executed. After this control would pass to line 8. Since line 7 had already been executed the indented line following line 8 would be skipped. Thus at any one running of the program

Now let us examine a different scenario

Suppose that floatGross has a value of 800, then at line 6 the condition will be false since 800 is not less than 500. If this is the case programme control jumps from line 6 directly to line 9, thus skipping line 7. Again with floatGross having a value of 800 then at line 9 floatTax would be given a value of
125 +(800-500) * 0.33
This is equal to
125 + 300 * 0.33
This simplifies to
125 + 99
which is
224.

Figure 2 below shows two runnings of the programme, the first where floatGross has a value of 400 and the second where the same variable has a value of 800

Fig 2
Go to top

Complex Decisions: the if..elif..else construct

The if..else construct, which we have encountered in the previous lesson is fine when we have only to choose between two alternatives. On the other hand if we have to choose between a larger number of alternatives, the if..else construct, even though it can handle the situation, can be very clumsy. In this situation we use the if..elif..else construct.

In order to explore this construct we shall extend our payroll application further so that it can handle superannuation calculation. Superannuation calculation normally involves taking a percentage of an employee’s pay and putting it into his superannuation account. The method we shall employ to calculate the contributions is that each employee is given a super code number and this number determines the percentage of their gross that will be deducted and put into their super account. In our case the percentage taken will be according to the following table:

Super CodePercentage
00%
15%
210%
315%
420%

What this means is that if the superannuation code is 0 then the employee pays no superannuation, whereas if the superannuation code is 1 then the employee pays 5% of his gross pay towards the superannuation. The same applies for the other possible values of the superannuation code.

On the other hand, if the value for superannuation is any number other than those in the range 0 – 4, then calculation proceeds and a message is printed indicating that a faulty superannuation code has been entered, but no contributions are deducted from the employee’s pay.

Below in Listing 3 we have the next upgrade on our payroll programme, where this version is able to work out superannuation contributions based on a superannuation code entered by the user. As always many of the lines in the programme correspond with its previous version, and again we will only concentrate on the new lines that we have added. These are line 5 and lines 11 - 24

Listing 3
                        #C4Payroll Complex Decisions1.py
                        strName=input("Enter employee's full name:  ")
                        floatHours=float(input("Enter value for hours:  "))
                        floatRate=float(input("Enter value for rate:  "))
                        intSuperCode=int(input("Enter value for Superannuation code:  "))
                        floatGross=floatHours * floatRate
                        if floatGross < 500:
                            floatTax=floatGross * 0.25
                        else:
                            floatTax=125+(floatGross - 500) * 0.33
                        if intSuperCode == 0:
                            floatSuperAmt = 0.0
                        elif intSuperCode == 1:
                            floatSuperAmt = floatGross * 0.05
                        elif intSuperCode == 2:
                            floatSuperAmt = floatGross * 0.1
                        elif intSuperCode == 3:
                            floatSuperAmt = floatGross * 0.15
                        elif intSuperCode == 4:
                            floatSuperAmt = floatGross * 0.2
                        else:
                            floatSuperAmt = 0.0
                            print("Faulty value for super code")
                            print("Superannuation is calculated as zero")
                        floatNet=floatGross-floatTax-floatSuperAmt
                        print("Gross is " + str(floatGross))
                        print("Tax is " + str(floatTax))
                        print("Superannuation contribution is:  " + str(floatSuperAmt))
                        print("Net is " + str(floatNet))
                    

Line 5 is similar to the two lines above it except that instead of using the function float() it uses the function int() in order to convert the user’s input into an integer value, before storing that value in the variable intSuperCode. Also notice that the name of the variable starts with ‘int’ as a reminder to the user that the value contained in it is an integer.

Lines 11 – 24 contain the if..elif..(else). This is a construct used when we need to check a variable for a number of values and perform a different action depending on the value. In our case here we need to check the variable intSuperCode for values in the range 0 – 4 inclusive.

At line 11 it starts off with a normal if construct where intSuperCode is checked for a value of zero. If it does have a value zero then line 12 is executed and zero is stored in floatSuperAmt. Once this line is executed then programme control jumps out of the if..elif..else construct and execution resumes at line 25.

If, on the other hand, intSuperCode has a value other than zero then line 12 is skipped and at line 13 it is checked for having a value of 1. Similarly at lines 15, 17 and 19 it is checked for the values 2, 3 and 4. Supposing it has a value of 2 then it is tested for a value of 1 at line 13. Since this will return a value of false line 14 is ignored and the variable is tested for a value of 2 at line 15. This will return a value of true and therefore line 16 is executed, where floatSuperAmt is given a value which is 10% of floatGross. Once this line is executed programme control jumps out of the if..elif..else construct and execution resumes at line 25.

Finally supposing that the value of intSuperCode is 12 or -5 or any other value that is not in the range 0 – 4, what happens with our construct? What happens is the value of intSuperCode is tested at lines 11, 13, 15, 17 and 19 and false is returned in all cases. Finally execution arrives at line 21 where it meets the else keyword. The fact that programme execution has reached the else means that intSuperCode has a value other than numbers in the range 0 – 4 and the code beyond beyond else, i.e. lines 22, 23 and 24, will be executed in order to deal with this situation. In our case what we wish to do is firstly inform the user that an out-of-range code was entered for the superannuation code and to set the superannuation contributions to zero.

Fig 3 below shows the different outputs that the programme produces when on successive runnings the values 2, 3, 4 and 5 were entered for the superannuation code.

Fig 3
Go to top

Practice

Copy the code in Listing 1into the programme into a text processor and save it. Next run it a number of times. Use different combinations of hours and rate so that some give a gross less than 500 and others give a gross greater than 500. Before running the programme each time first check using pen and paper what the values for the gross, tax and net should be, then check that the programme outputs against the same results.

Exercise

Regarding lines 6 to 9 in Listing 2 above answer the following questions:

  1. If floatGross has a value of 450 what line or lines would be executed?
  2. If floatGross has a value of 560 what line or lines would be executed?
  3. If floatGross has a value of 499 what would the value of floatTax be?
  4. If floatGross has a value of 501 what would the value of floatTax be?
  5. If floatGross has a value of 700 what would the value of floatTax be?

Go to top

Summary

The if and if..else constructs

What is an if construct?

An if construct allows a program to decide whether to perform a set of instructions is run or not.

Usually the program makes the decision by comparing a value held in a variable and a constant.

If the value held in the variable and the constant are the same then the set of instructions is run, otherwise nothing happens

How do we determine how many lines of code are controlled by the if construct?

In Python the lines influenced by an if construct are indented four spaces deeper than the if construct itself

What is the drawback of the if construct?

It can only take action if a condition is true. It takes no action if the condition is false

What is an alternative to the if construct?

The alternative is the if...else construct. It specifies what to do if the condition is true and what to do if the condition is false

How does the if..else construct work?

The if component compares two values.

If the comparison returns true then the indented block following the if is executed and the indented block following the else is skipped.

If the comparison returns false then the indented block following the if construct is ignored and the block following the else is executed.

Go to top

Assignments

Assignment Part 2

Modify the application you have created for Assignment Part 1 so that it can process customer discounts. If the subtotal is more than $100 then the customer receives a 5% discount otherwise no discount is given. The discount must be subtracted from the subtotal before the GST is calculated.

You must add an extra variable to your programme in order to hold the value of the discount. The value of the discount must be printed along with the other values.

Assignment Part 2.1

Modify the program for the above assignment so that it can cater for a variety of discount codes.

Casual customers have a discount code of zero, while business customers have a discount codes varying from 1 to 6. The relationship between the discount code and percentage is shown in the following table.

Discount CodePercentage
00%
15%
27%
310%
415%
520%
625%

Other than the calculation of the percentage, the rest of the processing is the same as in Part 2 above.

Go to top