A simple Python Programme

Variables SimplePayrollProgramme InteractivePayrollProgramme Exercise Assignment Part 1

Learning Outcomes

On completion of this chapter you will know:

Download pdf version

Introduction

When dealing with computers, programming means giving the computer instructions on how to perform a particular task.  All applications that you work with on a computer such as Word, Excel, image processing applications, video editing software etc. are all computer programmes.  Of course those programmes are a lot more complex than the simple programmes that you will start with, but by the end of the course you may have an idea on how to tackle one of them.  Also programmes such as those mentioned above were not written by one person but by a team of perhaps one hundred programmers.  In fact big applications such as those mentioned are strictly not programmes but a group of hundreds of small programmes that interact with each other.

In this course you will start by building very small and simple programmes that will get bigger and more sophisticated as you learn more techniques, until eventually you will have a small business application that will be similar to an accounting application.

Variables

Go to top

The manipulation of variables is at the heart of computer programming.  To the non-programmer variables are associated with algebra.  A typical algebraic problem would be as follows:

If x = 5, y = 9 and z=3, what is the value of 2x+3y-5z?

The solution to this of course is that if x is 5 then 2x is 10, if y is 9 then 3y is 27 and if z is 3 then 5z is 15.  Thus the expression 2x+3y-5z equates to 10+27-15 which is 22.

We shall look at one more example of algebraic expression.  In calculating a person’s pay we multiply the number of hours the person has worked with his hourly rate.  Thus if a person has worked x hours and if his hourly rate is y, then his pay is xy.  On a particular week if the person has worked 30 hours and if his rate is $8 per hour then we can state the problem as follows:

If x = 30 and y = 8, what is the value of xy?

In this case the solution is the same as above, i.e. if x is 30 and y is 8 then xy is 30 multiplied by 8, which is 240.

As stated earlier, programming a computer involves the manipulation of variables and they are manipulated in exactly the same way as they are manipulated in algebra.  This means that we assign a value to each variable in the expression and then perform the calculation specified in that expression.

There are, however, a few differences between how we use variables in algebra and how we use them in programming.  Some of the differences are as follows:

  1. In algebra we use a single letter to denote a variable.  The most common letters are x, y, z followed by a, b, c.  In complete contrast to this, the names of the variables used in programming can be as long as we want them to be.  Thus in our payroll example above, instead of If x = 30 and y = 8, what is the value of xy we would have the following: if hours-worked = 30 and hourly-rate = 8, what is the value of hours-worked * hourly-rate?
     A computer programme would solve the problem as follows:

Hours = 30

Rate = 8

Gross = Hours * Rate

print (Gross)

 

  1. In algebra, variables represent only numeric values.  In programming, variables can certainly represent numeric values, but they can also represent text and a variety of other objects such as data stored in databases etc.  However we need not concern ourselves with this use of variables until later in the course.

A simple Payroll Programme

Go to top

For our example we shall extend the example above to do a fuller payroll calculation in that the programme will also calculate the gross, tax and net.  The calculation will, however, be fairly simplistic.  The sequence of the calculations will be as follows:

1.      Gross will be calculated by multiplying the hours by the rate

2.      Tax will be calculated as 25% of the gross

3.      Net will be calculated by subtracting the tax from the gross

The code for the programme is shown below in Listing 1

Listing 1

1

#C2A Simple Payroll Programme

2

floatHours=20.0

3

floatRate=15.0

4

floatGross=floatHours * floatRate

5

floatTax=floatGross * 0.25

6

floatNet=floatGross-floatTax

7

print("Gross is " + str(floatGross))

8

print("Tax is " + str(floatTax))

9

print("Net is " + str(floatNet))

 

Note:  The line numbers shown above in Listing 1 are for clarity and ease of reference only.  They are not part of the code.  Thus, if you are copying the code, do not copy the line numbers along with it.

As stated earlier line 1 contains a comment which simply documents the name of the programme and thus the real programme starts at line 2

Lines 2 and 3 declare and give values to two variables, floatHours and floatRate.  We stated earlier that variables can be given longer names than they are given in algebra.  Here we will elaborate more on this idea.  Variables names must be able to indicate both the type of data that is to be stored in the variable and what that data is to be used for.  Python has no hard and fast rules for how this is to be done and thus the convention we shall follow in this course is similar to that that is used in Visual Basic, i.e. the first part of the variable name indicates the data type while the second part indicates what the variable is to be used for.

Using this convention line 2 declares a variable floatHours and assigns a value of 20.0 to it.  The fact that this variable will always, during the running time of the programme, hold a floating point number is not because the first half of its name is the word ‘float’ but because the value of 20.0 is assigned to it.  The ‘float’ part of its name simply indicates to the human being reading the programme that it is a variable designed to hold a floating point number.

Line 3 declares a variable floatRate and assigns a value of 15.0 to it. What we have said about floatHours applies also to floatRate.

In line 4 a third variable, floatGross, is declared.  Instead of assigning a constant value to it as was done in lines 2 and 3, here we add the product of  floatHours and floatRate to it.  In normal English line 4 could be rephrased as:

Multiply the values stored in the variables floatHours and floatRate and store the result in the variable floatGross.

Since floatHours had a value of 20.0 and floatRate a value of 15.0, multiplying the values of the two variables will give a result of 300.0.  Thus when line 4 finishes execution a variable named floatGross will be created and a value of 300.0 will be stored in it. We can determine that floatGross will hold a floating point number since the two variables whose values were multiplied, i.e. floatHours and floatRate were both floating point numbers.

Line 5 is somewhat similar to line 4.  A variable floatTax is created and the value of the variable floatGross is multiplied by 0.25 and then stored  in it.  Again the command in this line could be rephrased as:

Multiply the value stored in the variable floatGross by 0.25 and store the result in floatTax.

Since floatGross has a value of 300.0, multiplying this by 0.25 will give a result of 75.0 and this is the value that will be stored in floatTax.

Line 6 works in almost exactly the same way as lines 4 and 5, the only difference being that the operation here is subtraction instead of multiplication.  Again the line could be rephrased as:

Subtract the value of floatTax from the value of floatGross and store the result in floatNet.

Since floatGross has a value of 300.0 and floatTax a value of 75.0 then the value stored on floatNet will be 225.0

By now we have all of the calculations we need for the payroll complete and the results stored in the variables floatGross, floatTax and floatNet. All that is left for us now is to display the results to the user.  This is done by lines 7 – 9, all of whom use the print statement.  We have already met this statement in the first chapter where it was used to print out the text Hello World.

Line 7 uses the print function to print out the value of the variable floatGross.  This is to be preceded by the text constant “Gross is “.  Since text and numbers cannot be mixed in the same print function, the floating point variable floatGross must first be converted to text using the str() function.  This is then tacked on to the leading text and the result should be:

Gross is 300.0

The same applies to lines 8 and 9.  Figure 1 below shows the result.

Figure 1

A more interactive Programme

Go to top

Listing 1 above illustrates a simple Python programme and introduces the concept of variables and variable manipulation.  However in a real world situation the programme is completely impractical since it can only calculate the pay for someone whose hourly rate is 20 and who works only 15 hours.

If this was all that a programme could do, then in a situation where we had 20 employees, each working different hours and on a different hourly rate, we would need to have twenty different versions of the above programme!  Next imagine if their hours varied each week, and what about if they got a pay rise?  It would be simpler to use pen and paper.

Python programming, however, is not as stodgy as that.  Rather than hard coding the values of the hours and rate into the programme we can instead allow the user to directly enter values for hours and rate into the programme and then allow the programme to calculate the gross tax and net and finally print out the results.  Our next programme, which is simply a variation of the one above, does exactly that.

Listing 2

1

#C2Interactive Payroll Programme

2

strName=input("Enter employee's full name:  ")

3

floatHours=float(input("Enter value for hours:  "))

4

floatRate=float(input("Enter value for rate:  "))

5

floatGross=floatHours * floatRate

6

floatTax=floatGross * 0.25

7

floatNet=floatGross-floatTax

8

print("Gross is " + str(floatGross))

9

print("Tax is " + str(floatTax))

10

print("Net is " + str(floatNet))

 

At first glance we see that this programme is slightly bigger than its predecessor – by one line.  That extra line, i.e. line 2, is added to make the programme more realistic since it does not make sense that we are going to pay someone unless we know the name of the person we are going to pay.  Another reason we have added that extra line to the programme is to better explain how data is received from the keyboard.

Line 2 is used to get a person’s name from the keyboard.  It uses the function input().  There are actually three steps in executing this line:

1.      First the function input() displays the prompt “Enter employee’s full name” on the console

2.      Then the function causes the programme to halt and wait for the user to enter data and press the enter key.

3.      Once the enter key is pressed the system takes over again and causes the data entered by the user to be stored in the variable strName.  Since a person’s name is obviously text the value entered by the user can be stored directly in the variable. 

Line 3 is somewhat similar but with an extra step.

1.      Firstly the prompt “Enter value for hours:  is displayed on the console.

2.      The programme is halted in order to wait for the user to enter data and press the Enter key.

3.      Instead of passing the user’s data directly to the variable floatHours, the data is passed instead to the function float().  The reason for this is that even though the user would have entered numeric data such as 22.50, as far as the programme is concerned it is not a number but the text item “22.50”.  We will need to work with this value later in order to calculate the gross pay.  In order to be able to do this we need to convert the text data to numeric, particularly to a floating point number.  For this reason the text data is passed directly to the function float().  This function then converts it to floating point number and finally stores the resulting numeric value in the variable floatGross.

The same logic applies to line 4 as to line three and thus there is no need to discuss it further.  Also lines 5 – 10 are identical to lines 4 – 9 in Listing 1 and for this reason there is no need to discuss them either.

Figure 2

Figure 2 shows the console after the user has entered values for both name and hours worked.  Currently the programme is waiting for the user to enter the value for the hourly rate – in other words it is halted at line 4.

Figure 3

The completed programme is shown in Figure 3.  It is displaying the input data and the calculated details for the payroll.

Exercise

Go to top

Copy the code in listing 2 into a text editor and save it.  Run it from the Python shell.  To ensure that it is running satisfactorily run it a number of times with different values for the hours and the rate.  Ensure that the values for the gross, tax and net correspond the values entered  for the hours and rate.

Assignment – Part 1

Go to top

Create a small application for calculating a customer’s total in a store.  Assume that the customer buys only one item type but that he may buy as many of that item as he wishes.  As an example the customer buys only tins of Sealord Tuna, but he may buy as many tins as he wishes.

The programme will ask the user for the description of the item, the amount of items that the customer has purchased and the unit price for those items.  The programme will calculate the subtotal by multiplying the amount sold by the unit price.  GST is then calculated by multiplying the subtotal by 0.1 – or by dividing the subtotal by 10.  The total charged to the customer is then calculated by adding the subtotal and the GST.  The values of the subtotal, GST and Total are then printed out in the console window.