In [1]:
print('hello world')


hello world

This was our first Python command.

Basic Python Explorations

There are some minor differences between Python2 and Python3. Let us consider an example:


In [3]:
# This is an inline comment: Python3
print('hello world')

# Python2
print 'hello world'


  File "<ipython-input-3-7d0e8552180e>", line 5
    print 'hello world'
                      ^
SyntaxError: invalid syntax

Basic Types

We now look at the different types of objects that Python offers: floats, integers, booleans, lists, dictionaries, etc.


In [5]:
1 * 1.0
a = 3
type(a)


Out[5]:
builtins.int

In [6]:
b = 3 > 5
print(b), type(b)


False
Out[6]:
(None, builtins.bool)

Let us now turn to containers: lists, dictionaries.


In [7]:
L = ['red', 'blue', 'green', 'black', 'white']
print(L)


['red', 'blue', 'green', 'black', 'white']

In [10]:
L[1], L[3:], L[3:15]


Out[10]:
('blue', ['black', 'white'], ['black', 'white'])

Lists are mutable objects, i.e. they can be changed.


In [11]:
L[1] = 'yellow'
print(L)


['red', 'yellow', 'green', 'black', 'white']

What is an example of an immutable object?


In [12]:
T = ('red', 'black')
T[1] = 'yellow'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-34af57d15608> in <module>()
      1 T = ('red', 'black')
----> 2 T[1] = 'yellow'

TypeError: 'tuple' object does not support item assignment

Let us now turn to the distinction between independent copies and references to objects.


In [17]:
print(L)
G = L
print(G,L)

# But now:
L[1] = 'blue'
print(G,L)

# Let us now create an independent copy:
G = L[:]
print('Independent: ', G, L)
L[1] = 'yellow'
print('Independent: ', G, L)


['red', 'blue', 'green', 'black', 'white']
['red', 'blue', 'green', 'black', 'white'] ['red', 'blue', 'green', 'black', 'white']
['red', 'blue', 'green', 'black', 'white'] ['red', 'blue', 'green', 'black', 'white']
Independent:  ['red', 'blue', 'green', 'black', 'white'] ['red', 'blue', 'green', 'black', 'white']
Independent:  ['red', 'blue', 'green', 'black', 'white'] ['red', 'yellow', 'green', 'black', 'white']

Miscellaneous

Formatting


In [2]:
import urllib; from IPython.core.display import HTML
HTML(urllib.urlopen('http://bit.ly/1K5apRH').read())


Out[2]: