The web site (Maths is fun) defines the word expression as "Numbers, symbols and operators (such as + and ×) grouped together that show the value of something". In the area of programming expression examples include:
intAmount + 5
intAmount * floatUnitPrice
As you may have guessed intAmount and floatUnitPrice are programming variables. In this lesson we shall use both variables and expressions in order to manipulate data input by the user in order to do whaever the fuck is to be done.
Expressions, Calculations and Assignment
Example 1
At first glance the code below looks very similar to the examples that we used in the provious lesson but we have introduced a new concept at line 4 where we use an expression and store the value of that expression in a variable - thus providing a new value that the user did not enter.
The code provides a very simple way to record a bulk sale in a store. The user is asked to enter the description of the item sold, the price of one single item and the amount that was actually sold. From the price of a single item and the amount sold the program calculates the total for the sale and stores it in a variable of its own.
In the algorithm above the first four commands correspond to lines 2 - 5 of listing 1. The fifth command in the algorithm, however requires three lines of code in Listing 1, i.e. lines 6-8. Also the last command in the algorithm requires four lines in Listing 1, lines 9 - 12. The reason the algorithm is so sparse here is that printing labelled outut has been thoroughly covered in on the previous page and students should be familiar with it by now.
From the examples and exercises in the previous lesson lines 2 - 4 should be familiar to you - they allow the user to enter values for the item description, price of a single item and the amount of items that were sold. Those values were stored in the variables strItemDescription, floatPrice and intAmountSold. The last two variables are the ones we are interested in.
Line 5 multiplies the values stored in the variables floatPrice and intAmountSold and then stores the result in the variable floatSaleValue. If we use the values entered in Fig 1 below then floatPrice should have the value 1200 stored in it and intAmountSold should have the value 16 stored in it. Thus when those two values are multiplied the result is 19200 which will be the value stored in the variable floatSaleValue.
Of he rest of the program lines 6 - 8 are purely for decorative purposes, so no need to discuss them. Lines 9 - 12 print the values of the program's variables along with descriptive labels as we saw in the previous lesson.
The image above shows a running of the code from Listing 1.
Example 2
The code below is simply an extension of Listing 1 with further expressions added. The cost of transporting the goods is added as well as calculating GST. Thus the total cost to the customer now becomes the total price of the goods plus GST plus the transport costs. We presume that GST rate is 10%, so it does not have to be entered by the user.
#Expression Example 2strItemDescription = input("Enter description of item: ")floatPrice = float(input("Enter price of one item: "))intAmountSold = int(input("Enter amount sold: "))floatTransportCost = float(input("Enter transport cost: "))floatSaleValue = floatPrice * intAmountSoldfloatGST = floatSaleValue * 0.1floatCostToCustomer = floatSaleValue + floatGST + floatTransportCostprint("#################")print("Sale Details")print("#################")print("Item Description: ", strItemDescription)print("Price: ",floatPrice)print("Amount Sold: ", intAmountSold)print("Total Sale Value: ", floatSaleValue)print("GST: ",floatGST)print("Customer to pay: ", floatCostToCustomer)
Listing 2
Lines 2 - 4 are the same as listing 1 and thus there is no need to discuss them.
At line 5 the value of the transport cost is received from the user and stored in the variable floatTransportCost.
Line 6 calculates the sale value exactly as in Listing 1 and stores the value in the variable floatSaleValue. line 7 calculates the value of the GST by multiplying the value stored in floatSaleValue by 0.1 and stores the result in floatGST.
The total charged to the customer would now be the sum of the total sale value, the GST amount and the transport cost. This is reflected in line 8 where the values of the variables floatSaleValue, floatGST and floatTransportCost are added up and stored in the variable floatCostToCustomer
The rest of the code is similar to that in Listing 1.
Fig 2 shows a running of the program in Listing 2.
There are a number of ways to document program code and we have already been using one of them - using meaningful variable names that informs the user what the variables are used for and the data type stored in them.
The programs we wrote and examined in the previous lesson were easy to keep track of because they were all ten lines or less long. Also their only actions was to retrieve text data from the user and print the same text data to the screen. Those programs had an input and an output section, but at first glance it was easy to see which was which since all of the output lines began with the print() function. Our programs by now are getting somewhat long and also contain a new section, where the data entered by the user is processed before being printed out - which means that our programs now have the traditional three sections: Input, Process and Output. Due to this extra complexity being introduced it is time for us to look at documenting our code so that the different sections of it will be clearly observable by the user.
To make the different sections of a program easily observable we add comments before each section stating what each section is doing. Comments are lines within the program code that will be ignored by the system when the program is running. In Python there are two ways to add comments. One of them is to begin a line with the "#" character. Once a line starts with this character the rest of the line is ignored by the system when the program is running.
The above code is the same as Listing 2 but with comments added. The comments are in groups of three. The firs set is lines 2 - 4, then 9 - 11 and 15 - 17. In those lines the actual comments are in lines 3, 10 and 16. The reason for the extra 'decorative' lines on each side of the comment line is to make the actual comment stand out if the text display is pure black and white. However if you are using an editor that renders comments in a different colour to the rest of the code then you don't need the extra decorative lines on either side of it.
This is a screenshot of Python's native editor, where comments are rendered in bright red, thus making them stand out from the rest of the text. In this case there is no need to add the 'decorative' lines on either side of them.
The exercises below are extensions of their equivalents in the lesson Variables.
Exercise 1
A customer in a store buys a number of the same item. The store is to deliver the item to the customer's residence. The delivery cost is added to the cost of the items
The data required for this transaction are:
Name of Customer
Description of items purchased
Number of Items sold
Cost of a single item
Delivery cost
Write a program that will collect this data from the user, store each data item in an appropriately named variable, calculate the cost of the sale by multiplying the cost of an item by the number of items sold. The total cost is calculated by adding the total cost of the items and the delivery cost Finally print out the data entered by the user as well as the calculated values. All data must be appropriately labelled. In the case of numeric data ensure that you use integers or floating point numbers as appropriate.
Exercise 2
Write a program that will collect data about a book. The data required include:
Title
Author
Genre
Price
Number of copies sold
The program must store each data item in an appropriately named variable. Total sales is calculated by multiplying Price by Amount sold. Both the data entered by the user and the calculated values must be printed with appropriate labels.
Exercise 3
Extend Exercise 2 so that the royalties for the author is calculated. The royalties are calculated as 10% of the total sales. Output must be similar to that for exercise 2 except that the royalties are also included.
Exercise 4
Modify Exercise 1 above so that data from three transactions can be entered by the user. The data from all three transactions must be printed with appropriate labels.
You are required to write a program that will collect details of an employee. The program will store each data item in an appropriately named variable. The data required are:
Employee Name
IRD number
Department
Hourly Rate
Hours worked
The value for hours worked should be an integer.
Once data entry is complete the Gross Pay is calculated by multiplying Hourly Rate by Hours Worked. Once the value of Gross Pay is calculated, Tax is calculated as 25% of the Gross Pay. Net Pay is calculated by subtracting Tax from Gross Pay. Both input value data and calculated values must be printed with appropriate labels.