3.3.2 Types

Your variables need not be numeric. There are several types. The most useful are described below:

Integer: Any whole number:

      >>> myinteger = 0
      >>> myinteger = 15
      >>> myinteger = -23
      >>> myinteger = 2378

Float: A floating point number, i.e. a non-integer.

      >>> myfloat = 0.1
      >>> myfloat = 2.0
      >>> myfloat = 3.14159256
      >>> myfloat = 1.6e-19
      >>> myfloat = 3e8
Note that although 2 is an integer, by writing it as 2.0 we indicate that we want it stored as a float, with the precision that entails.3.4 The last examples use exponentials, and in maths would be written $1.6\times10^{-19}$ and $3\times10^8$. If the number is given in exponential form it is stored with the precision of floating point whether or not it is a whole number.

String: A string or sequence of characters that can be printed on your screen. They must be enclosed in either single quotes or double quotes--not a mixture of the two, e.g.

      >>> mystring = "Here is a string"
      >>> mystring = 'Here is another'

Arrays and Lists: These are types which contain more than one element, analogous to vectors and matrices in mathematics. Their discussion is deferred until Section 3.10 ``Arrays''. For the time being, it is sufficient to know that a list is written by enclosing it in square brackets as follows: mylist = [1, 2, 3, 5]

If you are not sure what type a variable is, you can use the type() function to inspect it:

      >>> type(mystring)
      <type 'str'>
'str' tells you it is a string. You might also get <type 'int'> (integer) and <type 'float'> (float) 3.5.

EXERCISE 3.3
Use the interactive interpreter to create integer, float and string variables. Once you've created them print them to see how Python stores them.

Experiment with the following code snippet to prove to yourself that Python is case-sensitive, i.e. whether a variable named a is the same as one called A:

    >>> a = 1.2
    >>> print A

As a beginner you will avoid making mistakes if you restrict yourself to using lower-case for your Python functions and the names of your variables (but see also Section 2.4 on case-sensitivity).



Footnotes

... entails.3.4
floats can actually be less accurate than ints, however they can store fractional values and hence store numbers to greater precision; ints store exact values but are limited to whole numbers. eg. ``g=10'' is less precise than ``g=9.30665'' but it is a much more accurate value of the acceleration due to gravity at the Earth's surface!
... (float)3.5
If you've programmed in other languages before, you might be used to ``declaring'' variables before you use them. In Python this is not necessary. In fact there are several things Python ``does for you'' that may catch you out if you've programmed before. See Section 4.5, ``Python differences''.