Basic Python Explorations

This is our first IPython nootebook, which we are going to use to explore the very basics of Python programming,


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


hello world

As some you were asking about differences between Python2 and Python3, here is an example:


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

# Python2:
print 'hello world'


  File "<ipython-input-7-06425f45730f>", line 5
    print 'hello world'
                      ^
SyntaxError: Missing parentheses in call to 'print'

More broadly speaking, some function interfaces (here print function) change. We will encounter other examples as we move along. More information regarding this issue is available at https://wiki.python.org/moin/Python2orPython3.

Basic Types

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


In [11]:
1 * 1.0
a = 3.0
type(a)


Out[11]:
float

In [ ]:


In [8]:
b = 3 > 5
type(b)


Out[8]:
bool

In [12]:
a = int(a)
type(a)


Out[12]:
int

What about integer division?


In [ ]:
# Different between Python2 and Python3
3 / 2

Let us now turn to containers: lists, strings, etc.


In [14]:
L = ['red', 'blue', 'green', 'black', 'white']

In [ ]:


In [15]:
L[3], L[-2], L[3:], L[3:4]


Out[15]:
('black', 'black')

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


In [ ]:
L[1] = 'yellow'

There is an important distinction between independent copies and references to objects.


In [16]:
G = L
L[1] = 'blue'
L, G


Out[16]:
(['red', 'blue', 'green', 'black', 'white'],
 ['red', 'blue', 'green', 'black', 'white'])

In [17]:
G = L[:]
L[1] = 'yellow'
L, G


Out[17]:
(['red', 'yellow', 'green', 'black', 'white'],
 ['red', 'blue', 'green', 'black', 'white'])

How to work with lists, or objects more generally?


In [25]:
L.append('pink')
print(L)
L.pop()
print(L)


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

Now we turn to tuples, which are immutable objects.


In [27]:
T = 'white', 'black', 'yellow'
T


Out[27]:
('white', 'black', 'yellow')

In [28]:
T[1] = 'brown'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-2d15ea65174f> in <module>()
----> 1 T[1] = 'brown'

TypeError: 'tuple' object does not support item assignment

As you asked, here is one way to delete objects.


In [31]:
print(T)
del T
print(T)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-31-7178a4f8d6d2> in <module>()
----> 1 print(T)
      2 del T
      3 print(T)

NameError: name 'T' is not defined

Now, let us turn to dictionaries, which are tables that map keys to values.


In [33]:
tel = {'Yike': 4546456, 'Philipp': 773456454}
tel


Out[33]:
{'Yike': 4546456, 'Philipp': 773456454}

In [34]:
tel[1]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-34-788e37d7f635> in <module>()
----> 1 tel[1]

KeyError: 1

In [36]:
# What is Yike's telephone number?
tel['Yike']


Out[36]:
4546456

In [37]:
# How do we add Adam?
tel['Adam'] = 7745464
tel


Out[37]:
{'Yike': 4546456, 'Philipp': 773456454, 'Adam': 7745464}

In [38]:
# What keys are defined in our dictionary so far?
tel.keys()


Out[38]:
dict_keys(['Yike', 'Philipp', 'Adam'])

In [39]:
# Yike has a new telephone number.
tel['Yike'] = 77378797

Control Flow


In [42]:
a, b = 1, 5

if a == 1:
    print(1)
elif a == 2:
    print(2)
else:
    if b == 5:   
        print('A lot')
    
# Note the indentation.


1

In [43]:
for key_ in tel.keys():
    print(key_, tel[key_])


Yike 77378797
Philipp 773456454
Adam 7745464

Functions

It is important to distinguish between required, optional, and default arguments.


In [ ]:
def return_phone_number(book, name = 'Philipp'):
    ''' This unction returns the telephone nummber for the requested name.
    '''
    # Check inputs.
    assert (isinstance(name, str)), 'The requested name needs to be a string object.'
    assert (name in ['Yike', 'Philipp', 'Adam'])
    
    return book[name]

return_phone_number(tel)
return_phone_number(tel, 'Philipp')
return_phone_number(tel, 'Yike')
return_phone_number(tel, 'Peter')

Formatting


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


Out[2]: