MTSU
  CSCI 1170 - Computer Science I  
Roles of Variables (in Python3)

Variables in programs can be categorized by how they are used inside the program. We call these usage categories the roles of variables. For example, a variable whose value is never changed after initialization is considered a fixed value. Be careful not to confuse the roles of variables with the types of variables (integer, floating point, etc.)---they are different concepts.

Almost all variables used in programs can be identified as being in one of the following eleven role categories. The most commonly occurring roles are: fixed value, stepper and most-recent holder. Typically about 70% of variables in a program fall into one of these three categories. (On the other hand, some variables don't fit into any of the role categories below; this is uncommon, but not rare.)

The roles of variables (detailed below) are:


Note: The example programs below have line numbers included (as comments) for ease of reference. These line number comments have no effect on program execution.

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 below prompts the user for 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 variables can be used in different places in a program - twice on line 3 in the example.

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

(Note: The variable PI is also a fixed value.)


Icon for the role Stepper

Stepper variables go 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 variable can also be used, for example, for counting and traversing the indices of an array.

Icon for the role Most-recent holder

A variable is a most-recent holder if its value is the latest value processed of a certain group or simply the latest input value. The example program repeatedly (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 processed so far. The definition of "best" can vary depending on the task at hand: the most-wanted can mean, for example, the smallest number seen so far or, as another example, the biggest number seen so far, or, as one more example, the number closest to a certain value.

The example program below determines what is the smallest value of the ten integers given as an input. The variable smallest is a most-wanted holder because it is assigned (on line 5) 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:                        # 4
        smallest = number                        # 5
print("The smallest number was", smallest)       # 6 

(Note: 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 processed so far. The example program below accepts integers given as input one by one until the user inputs the number -999 after which the program calculates the average value of the inputs. The variable sum is a gatherer: the total of the inputs is gathered (on line 6) in it.

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

(Note: 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 below prompts the user for twelve integers and determines the biggest difference between successive input pairs of 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
biggest_diff = 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 > biggest_diff:                            # 8
        biggest_diff = current - previous                            # 9
    month += 1                                                       # 10
print("The biggest difference was", biggest_diff)                    # 11 

(Note: the variable month is a stepper, current is a most-recent holder and biggest_diff 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 that, once changed, is never reset to its original value. The example program below 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 any negative numbers appear among the input and, if at least one negative value is found, the variable will never return to its initial value of False.

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

(Note: the variable number is a most-recent holder and sum is a gatherer.)

A one-way flag can also be used, for example, to indicate whether one-time initializations must be made or not.


Icon for the role Temporary

A variable is a temporary if its value is needed only for a very short period and then is not needed again. 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 and stored in the temporary tax (on line 4) that is subsequently used (twice) in the next statement (on line 5) and not thereafter.

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

(The variable TAX_RATE is a fixed value and tax_free is a most-recent holder.)

A temporary is typically used for efficiency reasons (e.g., to store a computed value whose value is needed in several subsequent places) 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 that 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 = input("Enter a letter, x to quit: ")               # 2
while letter != "x":                                        # 3
    characters = characters + [letter]                      # 4
    letter = input("Enter a letter, x to quit: ")           # 5
print (characters)                                          # 6
length = len(characters)                                    # 7
if length>0:                                                # 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

A 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 "push" (on lines 4-5) and remove the most recently added element with the command "pop" (on lines 6-8). The stack is stored in the list stack that acts as a container

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

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


Icon for the role Walker

A walker variable is used to traverse a data structure. The example program implements a linked list that has a special head node. The user can insert new elements with the command "insert" (on lines 8-13) and print all the elements in the list with the command "print" (on lines 14-18). The variable p is a walker: it is used to traverse the whole list (via lines 15 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 = input("Enter command: ")                 # 6
while command != "quit":                           # 7
    if command == "insert":                        # 8
        p = head                                   # 9
        while p.next:                              # 10
            p = p.next                             # 11
        t = Node(input("Enter element: "))         # 12
        p.next = t                                 # 13
    elif command == "print":                       # 14
        p = head.next                              # 15
        while p:                                   # 16
            print (p.data)                         # 17
            p = p.next                             # 18
    command = input("Enter command: ")             # 19 

(The variable head is a fixed value, t is a temporary, and command is a most-recent holder)



Original handout created by and courtesy of jorma.sajaniemi@uef.fi & marja.kuittinen@uef.fi (9/24/2013)


https://www.cs.mtsu.edu/~untch/1170/public/RolesofVariables.html   (maintained by   Roland H. Untch)   $Date: 2021/02/15 23:47:56 $