Introductory Programming in Python: Lesson 4
Program State and Basic Variables

[Prev: Basic Output] [Course Outline] [Next: Basic Input]

The Concept of State

As we know, programs execute statements in sequential order. They flow through your code, left to right, top to bottom. As statements are executed, things happen; output is issued, calculations are done, and the state of your program changes. But what is state? Loosely put, state refers to all the data your program is dealing with and their current values at the point in time when a particular statement is about to be executed. Since the entire point of a program is to transform input data into some meaningful output data, it stands to reason that the program will modify the values of the data it is dealing with. This occurs in a stepwise fashion, statement by executed statement. But we need a way to record the state of our program in conveniently manageable units, which we shall call variables, as their value may vary over the course of program execution.

Variables each have a name, a type, and a value. A name is simply the name we choose to call a particular piece of data. For example, we previously called the bit of data representing the total number of apples held by everyone 'apples'. The value of apples started at 0, and as more people were inputed into the problem, the number of apples increased and so, accordingly, did the value of our variable 'apples'.

Type refers to the type of value a variable can have. Text is not the same as a number, thus they are considered different types. One could not for example add "apples" to the number 7. Python has five basic types:

int
Integers, e.g. 1, 179835646, -3, 0
string
Text strings, e.g. 'Alice', "The cat sat on the mat"
float
Real numbers, e.g. 0.0, 48747.23501, -0.5
bool
Boolean conditions, e.g. True, False
None
None is both a value and a type specifying a value that is not of any type nor has any actual value.

Assignment Statements

To create a new variable for use we simply assign it a value, by giving it a name and setting the name equal to the value. We do this by using the assignment statement which takes the form

variable_name = expression
Python 2.4.3 (#1, Oct	2 2006, 21:50:13) 
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "James"
>>>

Here we have created a new variable, whose name is 'name', and which has the value James. We did not explicitly state the type of 'name' to be a string, as python takes care of this for us. When assigning a value to a variable, python automatically sets the type of variable being assigned to the type of the value being assigned. If we go on to assign name again, this time with a different value

>>> name = "Jimbo"
>>>

The value of 'name' has changed. If we want to see what the value of a variable is we can simply print it:

>>> print name
Jimbo
>>>

James has disappeared. As far as the program is concerned James was never there. There is no James! Assigning a new value to a variable will obliterate the previous value of that variable. If you wish to keep the old value of a variable you need to save a copy, in a different variable.

>>> i = 1
>>> j = i
>>> i = 2
>>> print "i =", i, "and j =", j
i = 2 and j = 1
>>>

So let's look at what we've done, step by step.

  1. i = 1
    We create a new variable, called 'i', assign it a value of 1, and python sets it's type to 'int'
  2. j = i
    We create another new variable, this time called 'j', assign it a value of ... well what exactly? i is not a string because it's not in quotes, and it's not a number, so it's being treated as a variable. But what is 'i'? Variables are implicitly considered to be their current values. So i is implicitly considered to be 1 (it's current value)
  3. i = 2
    We assign a new value to 'i'. The old value of 'i' is discarded.
  4. print "i =", i, "and j =", j
    We output the current values of 'i' and 'j' respectively.

Step 2 highlights a number of important points about assignment. The assignment statement does something very specific. It changes the current value of the variable being assigned to the value of the expression to the right of the equals. This means that the value of the expression must be determined before actually changing the value of the variable. As you can see from the output produced by our little program, assignments do not 'hold true' over time in the same way as a similar statement in maths does. j = i does not mean that 'j' and 'i' are always equivalent. The only thing that can be certainly said about the relationship between 'j' and 'i' is that they will be equal directly after the assignment statement has been executed. Both before and after that point in time, all bets are off.

An assignment is not a description of a relationship between two expressions.
It effects a once off change in the value of one variable.

Consider the assignment statement x = x + 1. For those of you with inner mathematicians that are screaming loudly to get out, take a large stiff drink now! What we have is an assignment to a variable ('x') the value of an expression ('x + 1'). Let us suppose that currently the value of 'x' is 1. This assignment occurs as follows.

  1. x = x + 1
    The value of the expression 'x + 1' is determined. Since 'x' is 1, and complex expressions are built out of simple atomic expressions using operators like '+', we can transform the expression into '1 + 1' since variables are considered in expressions to be their current value.
  2. x = 1 + 1
    This is obviously 2, hence the value of the expression overall is 2.
  3. x = 2
    2 is assigned as the new value of 'x'.

Integers, Floats and Arithmetic Expressions

Obviously we want to be able do more than simply assign values to variables. We need to be able to manipulate and combine them in various ways. For integers and floats this leads directly to arithmetic notation, and its representations in python. Also how can we determine how variables of different types act when manipulated arithmetically. In general basic arithmetic expressions can be formed in much the same way as one would express them mathematically. If 'x' and 'y' are either integers or floats then

The above list describes various operators that can be used to form arithmetic expressions. But, suppose we have the expression 2+3*4. Which of the addition or the multiplication operators is applied first? One might think the operators are applied simply left to right, but as in maths, instead we have a well defined order of precedence specifying which operators are applied and in what order. The complete list of python operators and their precedence can be found here. In general python arithmetic operates exactly as it would in normal mathematics.

In the same way variables have a type, so too do expressions have a type associated with their value. The type of the value of an expression is generally determined by the types comprising the expression. For example, adding one integer to another in an expression always yields an integer, so the expression has type integer. But what happens when you mix two, or more, types in an expression. In general all participating sub-expressions have their type promoted to the most general type. By general, we mean 'most capable of representing all types involved'. For example, the value 0.5 cannot be represented by an integer, but the value 3 can be represented by a float as in 3.0. Hence adding a float to an integer means the integer gets promoted to a float and the type of the value of the expression as a whole will be a float. Division however acts slightly differently:

>>> print 4/2
2
>>> print 5/2
2
>>>

Four divided by two is two, no problems there. But five divided two is 2.5, not 2! Because both 5 and 2 are integers, python divides them as integers, in much the same way as we did in junior school. The number of times 2 goes into 5 completely is worked out, and the rest is considered the remainder. Because an integer can't represent the additional 0.5, it is simply dropped. If you want the exact value, divide by a float instead, and force promotion of the expression to a float:

>>> print 5/2.0
2.5
>>>

However, often we actually want the integer part of a division only, and equally so the remainder. Python provides us with an operator to get the remainder, namely modulo:

>>> print 5 % 2
1
>>> print "5 divided by 2 is ", 5/2, "remainder", 5 % 2
5 divided by 2 is 2 remainder 1
>>>

Strings and common operators

Strings can be manipulated too, but the operations we perform on them are fundamentally different. Assuming 's1' and 's2' are strings, and 'i' and 'j' are integers

Formalisation of the Concepts of Statements and Expressions

To recap, in a more formal way.

  1. Programs consist of sequences of statements
  2. Statements perform actions but do not have value
  3. Statements may act on expressions
  4. Expressions have a value, and when used in statements, their value is determined and substituted in place of the expression
  5. Expressions may be simple expressions such as numbers or variables whose values can be determined directly
  6. Expressions may be composed of simpler expressions combined using appropriate operators

Exercises

  1. What does the assignment statement do?
  2. What are the five basic variable types in python?
  3. If the integer variable i has the value 7, then what is the value of the expression 7/4. Why?
  4. How does one calculate the remainder (modulo) of an integer when divided by another number?
  5. Write a program that asks the user for a number from 1 to 31. Assume the first day of the month is a Sunday. Output the name of the weekday of the day of month the user entered.
  6. Write a program that outputs the letter "x" 1000 times on a single line, without intervening spaces.
  7. If s is a sting variable with the value "Harry's Hippie Hoedown", then what is the value of
    s + ": tickets only $5"
  8. If s is a sting variable with the value "Harry's Hippie Hoedown", then what is the value of
    s + ": tickets only $" + "5"*3
  9. What is the value of "ABBA was a Swedish band popular during the 80's"[0:4]?
  10. What is the value of "ABBA was a Swedish band popular during the 80's"[-15:-7]?
  11. If the string variable s has the value "ABBA was a Swedish band popular during the 80's", then what is the value of
    "BAAB"+s[4:11]+"Danish"+s[18:24]+"un"+s[24:-4]+"90's"
[Prev: Basic Output] [Course Outline] [Next: Basic Input]