In [5]:
print('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'
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.
In [11]:
1 * 1.0
a = 3.0
type(a)
Out[11]:
In [ ]:
In [8]:
b = 3 > 5
type(b)
Out[8]:
In [12]:
a = int(a)
type(a)
Out[12]:
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]:
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]:
In [17]:
G = L[:]
L[1] = 'yellow'
L, G
Out[17]:
How to work with lists, or objects more generally?
In [25]:
L.append('pink')
print(L)
L.pop()
print(L)
Now we turn to tuples, which are immutable objects.
In [27]:
T = 'white', 'black', 'yellow'
T
Out[27]:
In [28]:
T[1] = 'brown'
As you asked, here is one way to delete objects.
In [31]:
print(T)
del T
print(T)
Now, let us turn to dictionaries, which are tables that map keys to values.
In [33]:
tel = {'Yike': 4546456, 'Philipp': 773456454}
tel
Out[33]:
In [34]:
tel[1]
In [36]:
# What is Yike's telephone number?
tel['Yike']
Out[36]:
In [37]:
# How do we add Adam?
tel['Adam'] = 7745464
tel
Out[37]:
In [38]:
# What keys are defined in our dictionary so far?
tel.keys()
Out[38]:
In [39]:
# Yike has a new telephone number.
tel['Yike'] = 77378797
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.
In [43]:
for key_ in tel.keys():
print(key_, tel[key_])
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]: