How computers represent information: an introduction to data types

Most of us are familiar with variables in computer languages: strings of characters that represent some piece of information stored in the computer's memory. Likewise, most of us are familiar with the assignment operator, which directs the program to assign a particular value to a particular variable. Consider, for example, the Python statement a = 2:

In [1]:
a = 2
b = 2.

Under the hood, a space in memory is allocated, associated with a, and the value 2 is placed into that memory location.

All information in a computer program is binary

The decimal number 2 is recorded as the binary number 10.

Bits and bytes

A single binary digit is a bit. Bits are organized into bytes of 8.

An example

What happens under the hood when we execute the following commands in Python?

a = 2 b = 2. c = 2 + 2j d = '2' e = 'two'

We might even try: f = a == 2

or even:

def two(): pass g = two()

Basic data types in C and friends

int, float, double, char

(int variations: signed/unsigned, short/long)

Python basic data types

int (integer) in many compiled languages, 2 or 4 bytes. In Python 3, arbitrary precision, depending on size.

float (floating-point number) depends on platform, but commonly 64 bits. Represented using exponent and mantissa.

complex (complex number) includes real and imaginary part; use "j" to indicate.

bool (boolean) True or False

str (string) object containing a string of characters

NoneType only value is None

object more later!

In [2]:
a = 2
type(a)
Out[2]:
int
In [3]:
b = 2.
type(b)
Out[3]:
float
In [4]:
c = '2'
type(c)
Out[4]:
str
In [5]:
d = 'two'
print(type(d))
d[0]
<class 'str'>
Out[5]:
't'
In [6]:
c + d
Out[6]:
'2two'
In [7]:
e = 2 + 2j
type(e)
Out[7]:
complex
In [8]:
f = a == 2
type(f)
Out[8]:
bool
In [9]:
g = None
type(g)
Out[9]:
NoneType

A few more complex data types

list tuple dict

In [10]:
shopping = ['pear', 5, 3.14159]
shopping.append('honey')
shopping += ['88']
shopping[0] = 'peach'
shopping
Out[10]:
['peach', 5, 3.14159, 'honey', '88']
In [11]:
# tuple
mytup = (1, 2., '3')
mytup
Out[11]:
(1, 2.0, '3')
In [12]:
#mytup[0] = 5  # Illegal because tuples are immutable
In [13]:
d = {'spoons' : 13, 'frog' : 'green'}
type(d)
Out[13]:
dict
In [14]:
d['frog']
Out[14]:
'green'
In [15]:
d['gravity'] = 9.81
d
Out[15]:
{'spoons': 13, 'frog': 'green', 'gravity': 9.81}
In [16]:
print(d.keys())
print(d.values())
dict_keys(['spoons', 'frog', 'gravity'])
dict_values([13, 'green', 9.81])

Some common operators

'+' - * / ** % //

== != > < >= <= and not or