In [1]:
1, type(1)
Out[1]:
In [2]:
-1, type(-1)
Out[2]:
Almost all platforms map Python floats to IEEE-754 “double precision”.
In [3]:
3.14, type(3.14)
Out[3]:
Floating point math madness: http://0.30000000000000004.com
In [4]:
0.1 + 0.2
Out[4]:
In [5]:
'Hello World', type('Hello World')
Out[5]:
More on strings later
In [6]:
True, type(True)
Out[6]:
In [7]:
False, type(False)
Out[7]:
In [8]:
None, type(None)
Out[8]:
Type conversion is very easy and most of the time very intuitiv
In [9]:
float(2)
Out[9]:
In [10]:
int(3.99)
Out[10]:
In [11]:
str(3.14)
Out[11]:
In [12]:
str(10)
Out[12]:
In [13]:
float('3.14')
Out[13]:
In [14]:
int('3')
Out[14]:
float string to int will raise a ValueError
In [15]:
int('3.14')
However you can force it
In [16]:
int(float('3.14'))
Out[16]:
In [17]:
int(True), int(False)
Out[17]:
In [18]:
float(True), float(False)
Out[18]:
In [19]:
str(True), str(False)
Out[19]:
In [20]:
bool('Hello World')
Out[20]:
empty strings
In [21]:
bool('')
Out[21]:
All numbers different from 0 convert to True
In [22]:
bool(2), bool(1), bool(0.01), bool(0), bool(-0.001), bool(-1), bool(-2)
Out[22]:
In [23]:
pi = 3.14
pi
Out[23]:
In [24]:
pi0 = pi1 = pi2 = 3.14
pi0, pi1, pi2
Out[24]:
In [25]:
pos, pi, text = 1, 3.14, 'Hello World'
pos, pi, text
Out[25]:
In [26]:
a, b = 1, -1
print(a, b)
a, b = b, a
print(a, b)
In [27]:
result = 1 + 1
result
Out[27]:
In [28]:
result = 5 - 8
result
Out[28]:
Integer multiplication returns integer
In [29]:
result = -2 * 5
result
Out[29]:
Always returns float in Python 3. (In Python 2 integer division returns integer, 1 / 2 = 0).
In [30]:
result = 4 / 2
result, type(result)
Out[30]:
In [31]:
result = 4**2
result, type(result)
Out[31]:
In [32]:
result = 3.14**2
result, type(result)
Out[32]:
In [33]:
result = 3**2.23
result, type(result)
Out[33]:
Returning True or False
In [34]:
3.14 == 3.14
Out[34]:
In [35]:
'Hallo' == 'World'
Out[35]:
In [36]:
'3.14' != 3.14
Out[36]:
In [37]:
3.14 != 3.14
Out[37]:
Python ist probabliy most important Data structure are list.
In [38]:
l = [1, 'Hallo', 2, 2, 'Welt', print, [1, 'test', 1.92e-19], 3.14, 10]
l
Out[38]:
By index number starting at 0
In [39]:
l[1], l[4]
Out[39]:
negative number are possible
In [40]:
l[-2]
Out[40]:
positive
In [41]:
l[1:3]
Out[41]:
negative numbers
In [42]:
l[:-3]
Out[42]:
negative and positiv
In [43]:
l[1:-3]
Out[43]:
steps
In [44]:
l[1:-1:2]
Out[44]:
naming slices
In [45]:
center = slice(1, -1)
l[center]
Out[45]:
In [46]:
l[4] = 'Nano'
l
Out[46]:
In [47]:
l[2:4] = [3, 3]
l
Out[47]:
In [48]:
del l[5]
l
Out[48]:
In [49]:
len(l)
Out[49]:
In [50]:
l.append('am ende')
l
Out[50]:
Extending lists
In [51]:
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]
Using extend function
In [52]:
l1.extend(l2)
l1
Out[52]:
Using Operators
In [53]:
l1 += l3
l1
Out[53]:
In [54]:
l
Out[54]:
In [55]:
l.pop()
Out[55]:
In [56]:
l
Out[56]:
The del equivalent
In [57]:
last_item = l[-1]
del l[-1]
last_item
Out[57]:
In [58]:
l
Out[58]:
In [59]:
l.count(3)
Out[59]:
In [60]:
l
Out[60]:
In [61]:
l.index('Nano')
Out[61]:
In [62]:
l.index(3)
Out[62]:
In [63]:
help(l)
The differences between tuples and lists are, the tuples cannot be changed unlike lists.
In [64]:
t = (1, 'Hallo', 2, 2, 'Welt', print, [1, 'test', 1.92e-19], 3.14, 10)
t
Out[64]:
In [65]:
t[0]
Out[65]:
In [66]:
t[1:-1:2]
Out[66]:
In [67]:
t[0] = 4
In [68]:
del t[2]
In [69]:
help(t)
Dicts are unsorted (Key, Value) Pairs, internal realized by hash tables. They are equivalent to maps in C++, Java or Matlabt but they take every datatype as key and item.
In [70]:
d = {'Hello': 'World', 'pi': 3.14, print: 'function', 2.718: 'euler'}
d
Out[70]:
In [71]:
d['Hello']
Out[71]:
In [72]:
d.get('Hello')
Out[72]:
In [73]:
d[2.718]
Out[73]:
In [74]:
d[print]
Out[74]:
In [75]:
d['no_key']
In [76]:
d.get('no_key', 'key does not exist')
Out[76]:
In [77]:
d['Hello'] = 'Nano'
d['Hello']
Out[77]:
In [78]:
del d[print]
d
Out[78]:
In [79]:
d.pop(2.718)
Out[79]:
In [80]:
d
Out[80]:
Changing a key is not possible but
In [81]:
d['PI'] = d['pi']
del d['pi']
d
Out[81]:
In [82]:
d['pi'] = d.pop('PI')
d
Out[82]:
Using assignment for single pairs
In [83]:
d['pi'] = 3.14
d
Out[83]:
For adding dictionaries
In [84]:
d2 = {'python': 'in the lab', print: 'function', 'euler': 2.178}
d.update(d2)
d
Out[84]:
Views are dynamic
In [85]:
vview = d.values()
lview = list(vview)
vview, lview
Out[85]:
In [86]:
del d[print]
In [87]:
vview, lview
Out[87]:
In [88]:
d.keys()
Out[88]:
In [89]:
d.items()
Out[89]:
In [90]:
i = float(input('Enter number: '))
if i > 0:
print('positive')
if i < 0:
print('negative')
if i == 0:
print('zero')
In [91]:
i = float(input('Enter number: '))
if 0 <= i and i < 10:
print('between 0 and 10')
elif i >= 10:
print('bigger 10')
else:
print('negative')
In [92]:
l = [1, 'Hello', 2, 2, 'World', print, [1, 'test', 1.92e-19], 3.14, 10]
Check if item is in list
In [93]:
if 'Hello' in l:
print(True)
else:
print(False)
Check if item is not in list
In [94]:
if 'Hällö' not in l:
print(True)
'In' and 'not in' are available outside if statement
In [95]:
d = {'Hello': 'World', 'pi': 3.14, 'e': 2.718, 'h': 6.626e-34}
In [96]:
# Check keys
if 'pi' in d:
print('pi:', True)
if 'e' in d.keys():
print('e:', True)
# Check values
if 1.92e-19 not in d.values():
print('charge:', False)
'In' and 'not in' are not coupled to the if statement
In [97]:
print('Hello' not in l)
print('pi' in d)
In [98]:
a = True
# Good style
if a:
print('good style: is True')
# Bad style
if a is True:
print('bad style is True')
# Very bad style
if a == True:
print('very bad style: is True')
The typical text based adventure:
"You are at the roof of the the University Tower. Supringsly the tower is buring, what will you do:
In [ ]:
# C++ code
switch ( i ) {
case 0:
cout << 'You get a smoke intoxication and die.' << endl;
case 1:
cout << 'The elevator stucks and you die.' << endl;
case 2:
cout << 'You die.' << endl;
case 3:
cout << 'An UFO picks you up and your adventure starts.' << ;
}
In [99]:
i = int(input('Your choice? '))
if i == 0:
print('You get a smoke intoxication and die.')
elif i == 1:
print('The elevator stucks and you die.')
elif i == 2:
print('You die without pain.')
elif i == 3:
print('An UFO picks you up and your adventure starts.')
else:
print('You die because you are to stupid to pick a number.')
In [100]:
i = int(input('Your choice? '))
case = {0: 'You get a smoke intoxication and die.',
1: 'The elevator stucks and you die.',
2: 'You die without pain.',
3: 'An UFO picks you up and your adventure starts.'}
print(case.get(i, 'Wrong choice, you die'))
In [ ]:
int data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int i = 0; i < sizeof(data); i++)
{
std::cout << data[i] << endl;
}
In [ ]:
int[] data = new int[]{4, 8, 4, 2, 2, 1, 1, 5, 9};
for(int i = 0; i < data.length; i++)
{
System.out.println(array[i]);
}
In [101]:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(len(data)):
print(data[i], end=', ')
Iterate over a list
In [102]:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for datapoint in data:
print(datapoint, end=', ')
Iterate over a dictionary
In [103]:
d = {'Hello': 'World', 'pi': 3.14, 'e': 2.718, 'h': 6.626e-34}
Iterate over keys
In [104]:
for key in d:
print(key, end=', ')
In [105]:
for key in d.keys():
print(key, end=', ')
Iterate over values
In [106]:
for value in d.values():
print(value, end=', ')
Iterate over items
In [107]:
for item in d.items():
print(item, end=', ')
In [ ]:
for( int i: array )
{
System.out.println(i + ', ');
}
In [ ]:
for ( auto &i: data):
{
std::cout << i << ', ';
}
Some times you need the index, use enumerate
In [108]:
data = list(range(10))
for i, datapoint in enumerate(data):
data[i] = datapoint * 2
data
Out[108]:
In [109]:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [110]:
data * 2
Out[110]:
Use list comprehensions for this
In [111]:
[datapoint**2 for datapoint in data]
Out[111]:
Numpy arrays behave 'mathematically' but more on that later
In [112]:
import numpy as np
ary = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10] )
ary * 2
Out[112]:
Use filters with if statement
In [113]:
data = [-4, -3, -2, -1, 0 , 1, 1, 2, 3, 4]
In [114]:
[datapoint**2 for datapoint in data if datapoint >= 0]
Out[114]:
Nested for list comprehensions
In [115]:
[(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
Out[115]:
In [116]:
import random
import time
while random.random() > 0.005:
print('.', end='')
time.sleep(0.025)
In [117]:
import math
print('Calculate Sqr')
print('q: QUIT')
while True:
value = input('Put in number: ')
# Check for
if value == 'q':
print('Good bye')
break
value = float(value)
if value < 0:
print('Negative numbers are not allowed!')
continue
print('Sqr({}) = {}'.format(value, math.sqrt(value)))
Math provides basic mathematic functions and is part of the standart libary.
In [118]:
import math
In [119]:
def area(radius):
return math.pi * radius**2
def circum(radius):
return 2 * math.pi * radius
In [120]:
area(10)
Out[120]:
In [121]:
circum(10)
Out[121]:
In [122]:
def my_print(a):
a = a**2
print(a)
In [123]:
a = 10
my_print(a)
print(a)
In [124]:
def circle(radius):
area = math.pi * radius**2
circum = 2 * math.pi * radius
return area, circum
In [125]:
circle(10)
Out[125]:
The return value is a tuple
In [126]:
a = circle(10)
type(a)
Out[126]:
So this is equivalent
In [127]:
def circle(radius):
area = math.pi * radius**2
circum = 2 * math.pi * radius
return (area, circum)
a = circle(10)
type(a)
Out[127]:
Some times you want to return a list or some othe other datatype
In [128]:
def circle(radius):
area = math.pi * radius**2
circum = 2 * math.pi * radius
return [area, circum]
a = circle(10)
type(a)
Out[128]:
In [129]:
def pythagoras(a, b):
return math.sqrt(a**2 + b**2)
In [130]:
pythagoras(1, 3)
Out[130]:
In [131]:
pythagoras(1, b=3)
Out[131]:
In [132]:
pythagoras(a=1, b=3)
Out[132]:
In [133]:
def cuboid(a, b, c):
volumn = a * b * c
return volumn
In [134]:
cuboid(2, 3, 2)
Out[134]:
In [135]:
def cuboid(a, b=1, c=1):
return a * b * c
In [136]:
cuboid(2)
Out[136]:
In [137]:
cuboid(2, 3)
Out[137]:
In [138]:
cuboid(2, c=3)
Out[138]:
In [139]:
cuboid(2, 3, 4)
Out[139]:
You can make all arguments default but not very common
In [140]:
def cuboid(a=1, b=1, c=1):
return a * b * c
In [141]:
cuboid()
Out[141]:
In [142]:
def some_function(a, *args):
print(args, type(args))
for value in args:
print(value, end=', ')
In [143]:
some_function(1, 2, 3, 'Hallo', 4, [2, 3, 4])
In [144]:
def some_function(a, *args, **kwargs):
print(args, type(args))
for value in args:
print(value, end=', ')
print()
print(kwargs, type(kwargs))
for pair in kwargs.items():
print(pair)
In [145]:
some_function(1, 2, 3, 'Hallo', 4, [2, 3, 4], name='python', where='in the lab', nr=10)
When is this usefull
In [146]:
import matplotlib.pyplot as plt
%matplotlib inline
Wrapping functions
In [147]:
def plot_sqrt(xdata, ydata):
ydata_2 = [point**2 for point in ydata]
return plt.gca().plot(xdata, ydata_2)
In [148]:
plot_sqrt(range(11), range(11))
Out[148]:
In [149]:
def plot_sqrt(xdata, ydata, *plot, **kwplot):
ydata_2 = [point**2 for point in ydata]
return plt.gca().plot(xdata, ydata_2, *plot, **kwplot)
In [150]:
plt.figure()
plot_sqrt(range(11), range(11), ':o', c='red')
Out[150]:
In [151]:
plot_global = {'color':'green', 'ls':'--', 'lw':3, 'marker':'o', 'ms':5}
In [156]:
from collections import ChainMap
def plot_sqrt(xdata, ydata, *plot, **kwplot):
ydata_2 = [point**2 for point in ydata]
# Override global plot config with local plot config
kwplot = ChainMap(kwplot, plot_global)
return plt.gca().plot(xdata, ydata_2, *plot, **kwplot)
In [157]:
plot_sqrt(range(10), range(10))
Out[157]:
In [158]:
plot_sqrt(range(10), range(10), marker='D')
Out[158]:
In [159]:
d0 = {'class':'Python in the lab', 'time':'16:15', 'location':'somewhere'}
d1 = {'location':'seminar room', 'people':10}
In [160]:
d = d0.copy()
d.update(d1)
d
Out[160]:
In [162]:
from collections import ChainMap
dict(ChainMap(d1, d0))
Out[162]:
In [ ]:
# Very hot Python 3.5 shit
d = {**d0, **d1}
In [163]:
plot_global = {'color':'green', 'ls':'--', 'lw':3, 'marker':'o', 'ms':5}
def plot_sqrt(xdata, ydata, *plot, ax=None, **kwplot):
ydata_2 = [point**2 for point in ydata]
if ax is None:
ax = plt.gca()
# Override global plot config with local plot config
kwplot = ChainMap(plot_global, kwplot)
return ax.plot(xdata, ydata_2, *plot, **kwplot)
In [164]:
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
plot_sqrt(range(-10, 11), range(-10, 11), ax=axs[1], marker='D', ms=10)
plot_sqrt(range(-10, 11), range(-10, 11), ax=axs[0], color='red', ls=':')
Out[164]:
In [165]:
plot_global = {'color':'green', 'ls':'--', 'lw':3, 'marker':'o', 'ms':5}
def plot_sqrt(xdata, ydata, *plot, **kwplot):
"""Plot the square of xdata as a function of ydata.
*plot and **kwplot are optional arguments of matplotlib.pyplot.plot
"""
ydata_2 = [point**2 for point in ydata]
kwplot = ChainMap(plot_global, kwplot)
return plt.gca().plot(xdata, ydata_2, *plot, **kwplot)
In [166]:
help(plot_sqrt)
In [167]:
a = 'Hello'
b = 'World'
l = [a, b]
Some words on TAB completion
In [ ]:
l.<TAB>
l.
Nested TAB completion
In [ ]:
a.<TAB>
a.
In [ ]:
l[0].<TAB>
l[0].
In [169]:
%config IPCompleter.greedy = True
In [ ]:
l[0].<TAB>
l[0].
Getting help in the notebook or IPython
In [ ]:
l.append(<TAB>)
l.append()
In [170]:
l.append?
In [171]:
plot_sqrt??
Getting help everywhere else
In [168]:
help(l.append)