Roles of Variables

Variables have in programs some typical uses that are called roles of variables. For example, a variable whose value is never changed after initialization is called a fixed value. Roles of variables must not be mixed up with the types of variables (integer, floating point, etc.) since the concept of roles is a classification telling what kind of a task a variable has in a certain program.

The following eleven roles are enough to cover almost all variables in simple programs. Roles appearing the most often are fixed value, stepper and most-recent holder which cover about 70 % of all variables. On the other hand, all variables don't necessary have any of the roles listed below.

The roles of variables (presented more accurately below) are:

The meaning of line numbering in example programs is to ease refering to lines. Line numbers have no effect on program execution since they are comments in Python.

Icon for the role Fixed value

The role of a variable is a fixed value, if its value is not changed in run-time after initialization. The example program asks user the radius of a circle and then prints out the area of that circle. Variable r is a fixed value. This variable gets its value (on line 2) during the run-time only once. The value never changes after that. Fixed value can be used in different places in a program - twice on line 3 in the example.

pii = 3.14                                            # 1
r = float(input("Enter the radius of a circle: "))    # 2
print ("The area of the circle is", pii*r*r)          # 3 

(The variable pii is a fixed value, also.)

Icon for the role Stepper

Stepper goes through a succession of values in some systematic way. Below is an example of a loop structure where the variable multiplier is used as a stepper. The example program outputs a multiplication table while the stepper goes through the values from one to ten.

multiplier = 1                                  # 1
while multiplier <= 10 :                        # 2
    print (multiplier, "* 3 =", multiplier*3)   # 3
    multiplier += 1                             # 4 
A stepper can also be used, for example, for counting and traversing the indexes of an array.

Icon for the role Most-recent holder

A variable is a most-recent holder, if its value is the latest gone through value of a certain group or simply the latest input value. The example program repeteadly (on line 3) asks the user for the input until the input is valid. In this program the variable s is a most-recent holder since it holds the latest input value at the time.

s = 0                                                                # 1
while s <= 0 :                                                       # 2
    s = float(input("Enter the length of the side of a square: "))   # 3
print ("The area of the square is", s*s)                             # 4 

Icon for the role Most-wanted holder

The value of a most-wanted holder is the "best" or otherwise the most-wanted value out of the values gone through so far. The exists no restrictions for measuring the superiority of the values: the most-wanted can mean, for example, the smallest or the biggest number or a number closest to a certain value.

The example program finds out which is the smallest of the ten integers given as an input. The variable smallest is a most-wanted holder since it is given (on line 4) the most recent value if it is smaller than the smallest one so far.

smallest = int(input("Enter a number: "))        # 1
for i in range(9) :                              # 2
    number = int(input("Enter a number: "))      # 3
    if number < smallest : smallest = number     # 4
print ("The smallest number was", smallest)      # 5 

(The variable i is a stepper and number is a most-recent holder.)

Icon for the role Gatherer

The value of a gatherer accumulates all the values gone through so far. The example program accepts integers given as an input one by one until the user inputs the number -999 after which the program calculates the mean value of the inputs. The variable sum is a gatherer: the total of the inputs is gathered (on line 7) in it.

count = 0                                                    # 1
sum = 0                                                      # 2
number = 0                                                   # 3
while number != -999 :                                       # 4
    number = int(input("Enter a number, -999 to quit: "))    # 5
    if number != -999 :                                      # 6
        sum += number                                        # 7
        count += 1                                           # 8
if count :                                                   # 9
    print ("The average is", sum / count)                    # 10 

(The variable count is a stepper and number is a most-recent holder.)

Icon for the role Follower

A follower always gets the old value of another known variable as its new value. The example program asks the user for twelve integers and finally tells the biggest difference between the two successive input integers. The variable previous is a follower: it follows the variable current (on line 6).

previous = int(input("Enter the 1. value: "))                        # 1
current = int(input("Enter the 2. value: "))                         # 2
biggestDiff = current - previous                                     # 3
month = 3                                                            # 4
while month <= 12 :                                                  # 5
    previous = current                                               # 6
    current = int(input("Enter the " + repr(month) + ". value: "))   # 7
    if current - previous > biggestDiff :                            # 8
        biggestDiff = current - previous                             # 9
    month += 1                                                       # 10
print ("The biggest difference was", biggestDiff)                    # 11 

(The variable month is a stepper, current is a most-recent holder and biggestDiff is a most-wanted holder.)

Followers are used a lot with linked data structures to point the data element previous to the one in process.

Icon for the role One-way flag

A one-way flag is a Boolean variable which once changed cannot get its original value anymore. The example program outputs the sum of input numbers given by the user and tells if there were any negative numbers among the inputs. The one-way flag neg watches (on line 7) whether there appears any negative numbers among the inputs and if at least one negative value is found, the variable will never return to value false.

sum = 0                                                               # 1
neg = 0                                                               # 2     
number = 1                                                            # 3     
while number :                                                        # 4     
    number = int(input("Enter a number, 0 to quit: "))                # 5     
    sum += number                                                     # 6     
    if number < 0 : neg = 1                                           # 7  
print ("The sum is", sum)                                             # 8     
if neg : print ("There was at least one negative number in inputs")   # 9 

(The variable number is a most-recent holder and sum is a gatherer.)

A one-way flag can also be used, for example, to watch errors occuring in input data so that the program could ask the inputs again.

Icon for the role Temporary

A variable is a temporary if its value is always needed only for a very short period. The example program asks the user for tax-free prices and prints out the total price and the tax for each item. The tax is computed into the temporary tax (on line 6) which is immediately used twice in the next statement (on line 7).

taxRate = 16                                                            # 1
taxfree = 1                                                             # 2
while taxfree :                                                         # 3
    taxfree = float(input("Enter tax-free price (0 to quit): "))        # 4
    if taxfree :                                                        # 5
        tax = taxfree * taxRate / 100                                   # 6
        print ("Total price", taxfree+tax, "that includes tax", tax)    # 7 

(The variable taxRate is a fixed value and taxfree is a most-recent holder.)

A temporary is typically used for efficiency reasons (e.g., executing a computation, whose value is needed in several places, only once) or to clarify the program (e.g., computing the result in a variable even though the use of a variable would not be absolutely necessary). A temporary is also often used for swapping two data elements of an organizer.

Icon for the role Organizer

An organizer is a data structure which is used for reorganizing its elements after initialization. The example program asks the user characters one by one, assigns them into the organizer characters that is implemented as a list, reverses the order of the characters and finally outputs the characters in this reversed order.

characters = []                                             # 1
letter = "a"                                                # 2
while letter != "x" :                                       # 3
    letter = input("Enter a letter, x to quit: ")           # 4
    if letter != "x" : characters = characters + [letter]   # 5
print (characters)                                          # 6
length = len(characters)                                    # 7
if length :                                                 # 8
    i = 0                                                   # 9
    while i < length/2 :                                    # 10
        tmp = characters[i]                                 # 11
        characters[i] = characters[length-1-i]              # 12
        characters[length-1-i] = tmp                        # 13
        i += 1                                              # 14
print (characters)                                          # 15 

(The variable letter is a most-recent holder, length is a fixed value, i is a stepper and tmp is a temporary.)

An organizer can be used for sorting or for some other reorganization.

Icon for the role Container

Container is a data structure where elements can be added and removed. The example program implements a stack. The user can add new elements with the command "n" (on lines 5-6) and remove the most recently added element with the command "r" (on lines 7-9). The stack is stored in the list stack that acts as a container

stack = []                                             # 1
command = "x"                                          # 2
while command != "q":                                  # 3
    command = input("Enter command: ")                 # 4
    if command == "n":                                 # 5
        stack = stack + [input("Enter element: ")]     # 6
    elif command == "r" and len(stack) > 0 :           # 7
        print (stack[len(stack)-1], "removed.")        # 8
        del stack[len(stack)-1]                        # 9 

(The variable command is a most-recent holder.)

Icon for the role Walker

Walker traverses a data structure. The example program implements a linked list that has a special head node. The user can add new elements with the command "n" (on lines 9-13) and print all the elements in the list with the command "p" (on lines 14-18). The variable p is a walker: it traverses the whole list (on lines 11 and 18).

class Node:                                        # 1
  def __init__(self, data=None, next=None):        # 2
    self.data = data                               # 3
    self.next  = next                              # 4
head = Node()                                      # 5
command = "x"                                      # 6
while command != "q" :                             # 7
    command = input("Enter command: ")             # 8
    if command == "n":                             # 9
        p = head                                   # 10
        while p.next : p = p.next                  # 11
        t = Node(input("Enter element: "))         # 12
        p.next = t                                 # 13
    elif command == "p" :                          # 14
        p =head.next                               # 15
        while p :                                  # 16
            print (p.data)                         # 17
            p = p.next                             # 18 

(The variable head is a fixed value, t is a temporary, command is a most-recent holder, the attribute data is a fixed value and the attribute next is a fixed value.)


Last update: 24.9.2013

saja.fi@gmail.com
marja.kuittinen@uef.fi