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:
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
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.
i = 1
j = i
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)i = 2
print "i =", i, "and j =", j
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.
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.
x = x + 1
x = 1 + 1
x = 2
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
x + y
yields Additionx - y
yields Subtractionx * y
yields Multiplicationx / y
yields Divisionx % y
yields Modulo (or Remainder)x ** y
yields Exponentiation (or raising to the power of)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 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
s1 + s2
yields Concatenation"a"+"b"
yields "ab"s1 * i
yields Repetition"a" *
3
yields "aaa"s1[i]
yields Subscription (or indexing)"abc"[1]
yields "b". 'i' may be any expression evaluating to an integer.
Negative numbers may be used, where -i
means the i'th
last position.s1[i:j:k]
yields Slicing"The quick brown fox"[4:]
yields "quick brown fox""The quick brown fox"[-4:]
yields " fox""The quick brown fox"[:4]
yields "The ""The quick brown fox"[4:9]
yields "quick"."The quick brown fox"[::2]
yields "Teqikbonfx""The quick brown fox"[4:15:3]
yields "qcbw".s1[:]
yields Slicing of the entire string,
essentially making a complete copy of the string.To recap, in a more formal way.
7/4
. Why?s + ": tickets only
$5"
s + ": tickets only
$" + "5"*3
"ABBA was a Swedish band popular during the
80's"[0:4]
?"ABBA was a Swedish band popular during the
80's"[-15:-7]
?"BAAB"+s[4:11]+"Danish"+s[18:24]+"un"+s[24:-4]+"90's"