Python Introduction: Types

Let's evaluate some simple expressions.

In [1]:
3*2
Out[1]:
6
In [2]:
5+3*2
Out[2]:
11

You can use type() to find the type of an expression.

In [3]:
type(5+3*2)
Out[3]:
int

Now add decimal points.

In [4]:
5+3.5*2
Out[4]:
12.0
In [5]:
type(5+3.0*2)
Out[5]:
float

Strings are written with single (') or double quotes (")

In [6]:
"hello"
Out[6]:
'hello'

Multiplication and addition work on strings, too.

In [2]:
3 * 'hello ' + "sc15"
Out[2]:
'hello hello hello sc15'

Lists are written in brackets ([]) with commas (,).

In [8]:
[5, 3, 7]
Out[8]:
[5, 3, 7]

List entries don't have to have the same type.

In [9]:
["hi there", 15, [1,2,3]]
Out[9]:
['hi there', 15, [1, 2, 3]]

"Multiplication" and "addition" work on lists, too.

In [10]:
[1,2,3] * 4 + [5, 5, 5]
Out[10]:
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 5, 5]

Hmmmmmm. Was that what you expected?

In [1]:
import numpy as np

np.array([1,2,3]) * 4 + np.array([5,5,5])
Out[1]:
array([ 9, 13, 17])
In [ ]: