Python Programming

Variables

Introduction

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:

Go to top

Variables: text

In the previous lesson, when we looked at Sequence our program printed out details of a person: their name, age etc. The problem with this was that no matter how often we ran the program it would always print out the same data because that is all the the program was coded to do. Also without variables the program would not be able to do anything else.

By using variables in our next example we shall be able to enter our own data into the program and get it to print out that data for us. To manage this we must request the user to enter data at the keyboard, then this data will be stored in its own variable. Once all of the data has been received the values stored in all of the variables are printed out. The algorithm is below.

Listing 1
                    
                        #Variables Example 1
                        strName = input("Enter your name: ")
                        strSurname = input("Enter your surname: ")
                        strLocation = input("Enter your location: ")
                        strJob = input("Enter your job: ")
                        print("Thank you for the information")
                        print(strName)
                        print(strSurname)
                        print(strLocation)
                        print(strJob)
                    
                    

Now let us examine the code.

Line 1 begins with a "#" and therefore will be ignored by the system, so no need to discuss it further.

Line 2 is the first line of the program that will be activated. The first word there strName is the name of a variable. This means that it points to a location in memory where we can store data. But what data are we going to store there?

The rest of Line 2 consists of input("Enter your name: "). The input function prints the text "Enter your name:" and the waits for the user to enter data at the keyboard. In fact the function causes the system to wait as long at it takes the user to enter their name. Once the user has finished entering data and has pressed the Enter key, the data that the user entered is stored in the variable strName.

The above description of line 2 echoes the first line of the algorithm "Get name and store it in an appropriately named variable'. The system got the name using the input() function and stored it in a variable named strName. The firt half of this varible name indicates that the data is String type, i.e. text and that the actual data is someone's name.

Lines 3, 4 and 5 behave exactly the same way as line 2, and therefore there is no need to discuss them in detail.

Line 6 should be familiar to you from the previous lesson; it simply prints our the text that is between the brackets i.e. Thank you for the information. It signals that user input is complete and thus implements the fifth instruction in the algorithm - 'Signal end of input'.

Line 7, although it looks similar to line 6 at first glance, is quite different. Notice that the data between the brackets is not enclosed in quotation marks. This means the data is the name of a variable - strName in this case. Thus line 7 tells the system to retrieve the data stored in the variable strName and print it on the screen. Again it echoes the sixth instruction in the algorithm 'display the contents of the variable containing the person's name.

Similarly lines 8, 9 and 10 print the values stored in the variables strSurname, strLocation and strJob.

Fig 1: A running of the code in Listing 1

Below is a video that explains the program further.

A video that explains the working of the program shown in Listing 1

Before finishing this section on variables that hold text values, we shall look at a variation of Listing 1, which gives a somewhat better output.

Listing 2
                    
                        #Variables Example 2
                        strName = input("Enter your name: ")
                        strSurname = input("Enter your surname: ")
                        strLocation = input("Enter your location: ")
                        strJob = input("Enter your job: ")
                        print("Thank you for the information")
                        print("Name: ",strName)
                        print("Surname: ",strSurname)
                        print("Location: ",strLocation)
                        print("Job: ",strJob)
                    
                    

Listing 2 above is almost identical to Listing 1 apart from modifications to lines 7 - 10. The print() at line 7 now has two values between the brackets: the text Name : and the variable strName. Both of those values are separated by a comma.

When Line 7 is executed, the first item which is the text between the quotes is printed exactly as it is and the value of the variable strName - James in our example is printed next to it. Thus the output from Line 7 will be Name : James. The same applies to lines 8 - 10. The output from the modified program can be seen in Fig 2 below.

Fig 2
Go to top

Variables: numbers

In our previous examples on variables we only used text variables. Looking at Listing 2 we had variables like strName and strJob which would hold text data such as a person's first name or the description of their profession. Variables also can hold numeric data. To be specific there different types of numeric data that variables can hold, integers and floating point numbers are the ones we shall be looking at here.

Integers are whole numbers such as 15, 789 and 6. They are used to count whole items such as number of houses in a street, number of people living in a house etc. Floating point numbers are numbers with decimal places such as 12.5, 7.8989 and 0.43672. In our next example we shall use text variables, integer variables and floating point variables

First Example

The second and the third lines of Algorithm 2 are slightly different from their equivalents in Algorithm 1. The reason for he differences is that, as stated above, when a Python program accepts keyboard input it comes in as text, regardless of whether it contains only numeric digits only or not. If the data is meant to be numeric then it must be converted to either integer or floating point. For this reason the second and third instructions of Algorithm 2 insist that once data is received from the keyboard, it must be converted to either integer or floating point number before being stored in a variable. Without this conversion the data received from the keyboard would always be text.

Lines 3 and 4 of Listing 3 echo instructions 2 and 3 of Algorithm 2 by using the int() and float() functions to convert the inputs into either integer or floating point numbers before storing them in their appropriate variables.

Listing 3
                        
                            #Variable Example 3 - Numbers
                            strName = input("Enter full name: ")
                            intAge = int(input("Enter age: "))
                            floatHourlyRate = float(input("Enter hourly rate: "))
                            print("The following data was entered")
                            print("Name: ",strName)
                            print("Age: ", intAge)
                            print("Hourly Rate: ", floatHourlyRate)
                        
                    

Listing 3 above is an extension of Listing 2, where data is received from the user, then formatted and printed out with labels. The difference between the two is that Listing 3 uses numeric variables as well as text variables

At line 2 we use the input() function to get data from the keyboard

At line 3 the input() function is used again to get the person's age but this time it is inside the function int(). The reason for nesting input() inside int() is that input() takes data from the keyboard as text, regardless of whether we entered text or numbers. This time we want a numeric value since we are dealing with a person's age and therefore we need to convert it to an integer value. The function int() does this for us.

From this we can see that a lot of processing occurs at line 2:

  1. The input() function receives raw data from the keyboard as text
  2. The int() function converts the text data into an integer.
  3. The integer data is stored in the variable intAge

Line 4 is identical to line 3 except for the fact that the function float() converts the text data into a floating point number

The print() functions at lines 5 - 8 work exactly like their equivalents in Listing 2, and therefore do not need to be explained.

Fig 3

Above we see a sample output from Listing 3. Notice that age, which was an integer value has no decimal points, whereas hourly rate which was a floating point number has a decimal point.


Go to top

Second Example

Program based on this algorithm is shown below in Listing 4

                        
                            #Variable Example 4
                            strItemDescription = 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: "))
                            print("Data entry complete")
                            print("Item Description: ", strItemDescription)
                            print("Price: ",floatPrice)
                            print("Amount Sold: ", intAmountSold)
                            print("Cost of transpot: ", floatTransportCost)
                        
                    
Listing 4

The above code is similar to that in Listing 3 and no new concepts are introduced. We will however be using it as an introduction to expressions in the next lesson. The program's running and output is shown below.

Fig 4
Go to top

Input and Output

In our three example programs we start with getting data from the keyboard using the input() function. This function is so named because it allows the program to receive external data from the user via the keyboard. The process of allowing the program to receive external data is referred to as computer input.

Computers receive external data through a variety of sources and devices. These include barcode readers, scanning devices, touch screens - where would cellphone users be without it -mouse and the computer keyboard, which is what we are using for our input in this course.

Once it has receive external data as input the computer may process some or all of it and finally outputs it. In our case the processing is very little; lines 3 and 4 convert text data into either integer or floating poinnt data.

Like the input, the output data can be sent to a variety of devices. These devices include hard disk drives, flash drives, SSD cards, printers or the screen. In our examples the output device is the screen.

Go to top

Variable Naming Conventions

Most programming languages don't allow spaces in variable names. Variable names should fully describe the type of data that the variable holds and the use of the data within the program. In the programs we have looked at we have used variable names as floatHourlyRate. From this we can, at a glance determine what kind of data the variable holds. The first word - float - indicates that the variable will hold a floating point number i.e. a number with decimal places, while the rest of the name indicates that the value stored in that variable will be the amount that someone is paid for every hour that they work.

Again referring to the variable name floatHourlyRate notice that the 'h' of 'hourly' and the 'r' of 'rate' are capitalised. This is to allow the programemer to easily distinguish the different words that make up the variable name. This convention of capitalising the diferent words that make up the variable name is referred to as Camel Case.

An alternative to Camel Case is snake case, where the separate words that make up a variable name are separated by underscores and uses no capital letters. Thus our variable floatHourlyRate would be written in snake script as float_hourly_rate.

Either of the above conventions still clearly describe the type of data the variable holds and the use of that data within the program.

Go to top

Summary

In this lesson we introduced the concept of variables. This is a concept already familiar to those who have studied algebra and in the next lesson we shall be using programming variables in more or less the same way as we would be using their algebraic counterparts.

The two types of variables have some features in common. Any type of variable can have only one value at any one time. Although the value of a variable can change, that variable only holds the data item that has been most recently assigned to it and has no recollection of any previous values (Sorva, 2018).

Programming variables, however, differ from the algebraic variables in some respects. The most obvious one is their names. Algebraic variables has only one letter; the most common is x, followed by y and z. After that we have a, b and c and if things get involved we have the remaining 20 letters of the English alphabet. Programming variables, however, can have as many letters as are required in order to describe the data type stored in that variable and what that data is to be used for within the program. There are many conventions for naming programming variables Two that we have discussed here are Camel Script and snake script.

The greatest difference between algebraic and programming variables is that while the former only exist in our immagination as we are solving a mathematical problem, the latter physically exists as a group of registers in the computer's memory while the program that contains them is running.

Go to top

Exercises

Exercise 1

A customer in a store buys a single item. The store is to deliver the item to the customer's residence. There may be a delay of a number of days before the item is to be delivered. The data required for this transaction are:

  • Name of Customer
  • Location
  • Cost of item
  • Delivery charges
  • Number of days before delivery

Write a program that will collect this data from the user, store each data item in an appropriately named variable and finally print out the data with appropriate labelling. In the case of numeric data ensure that you use integers or floating point numbers correctly.


Go to top

Exercise 2

Write a program that will collect data about a book. The data required include:

  • Title
  • Author
  • Genre
  • Price
  • Amount sold

The program must store each data item in an appropritely named variable and then print each data item appropriately labelled.


Go to top

Exercise 3

Using Exercise 3 from the Sequence lesson as an example write a program that will allow the user to input details of three different individuals. The data items must be the same as what you used in the Sequence exercise. The data for all three individuals must be displayed with appropriate labels.


Go to top

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.

Go to top

Assignment

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 and once data entry is complete it will print out each data item using appropriate labels. The data required are:

The value for hours worked should be an integer.

Go to top