Introduction to python

First steps with python

Table of Contents

  1. Start Jupyter notebook

  2. Python as a calculator

  3. Defining variables (also print it out)

  4. Datatypes (integer, float, string, list, dictionary, tuple https://www.tutorialspoint.com/python/index.htm)

  5. Control flow

  6. Useful modules

    1. numpy (np.array, functions)

    2. matplotlib (plotting functions, plot 3d) [random point generation 3d box]

    3. other useful packages (I/O, database, and more)

  7. Defining functions

  8. Making modules

1. Start Jupyter notebook

Open a command line and type in:

    jupyter notebook

In theory it will appear in the browser.

Select destination folder and click on 'new' (in the upper right) and select 'python 2' from the menu.
It will open up a new notebook.

Let's try it out:

In [80]:
# This is a comment, so this line wont be interpreted. 
# I can write any comment to my future self...
print 'hello python!'  # This is how i print out a string
hello python!

2. Python as a calculator

In [81]:
3 * 2  # multiplication
Out[81]:
6
In [82]:
5 + 6  # addition
Out[82]:
11
In [83]:
2**10  # raising to power (2^10 would work too)
Out[83]:
1024
In [84]:
3.5 % 2  # modulo
Out[84]:
1.5

3. Defining variables

In [85]:
x = 3.14
In [86]:
print x
3.14
In [87]:
a = 'tree'
print a
tree
In [88]:
print a, x
tree 3.14
In [89]:
name = raw_input("What's your name? ")
print 'Hello '+name+'!'
What's your name? zsiga
Hello zsiga!

4. Data-types

A. Simple

In [90]:
b = True  # boolean

n = 234  # integer

r = 234.  # float

s = 'this is a string'  # string

print s
this is a string

B. More complex

List
In [91]:
lista = [1, 2, 3, 'abc', 'def', 'ghi', 'jkl', True, False, False, 34.5]  # creating a list

print lista[2:7]
[3, 'abc', 'def', 'ghi', 'jkl']
In [92]:
print lista
lista.append(876)
print lista
[1, 2, 3, 'abc', 'def', 'ghi', 'jkl', True, False, False, 34.5]
[1, 2, 3, 'abc', 'def', 'ghi', 'jkl', True, False, False, 34.5, 876]
In [93]:
print lista[-1]
876
Generating some lists
In [94]:
number_sequence1 = range(10)
print number_sequence1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [95]:
number_sequence2 = range(0, 10, 1)
print number_sequence2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [96]:
number_sequence3 = range(0, 10, 2)
print number_sequence3
[0, 2, 4, 6, 8]
In [97]:
number_sequence4 = range(20, 0, -3)
print number_sequence4
[20, 17, 14, 11, 8, 5, 2]
Tuple
In [98]:
a_tuple = (1, 2, 4, 'c')
print a_tuple, type(a_tuple)
print a_tuple[0]
(1, 2, 4, 'c') <type 'tuple'>
1
Dictionary
In [99]:
dictionary = {'alma': 'apple', 'narancs': 'orange', 1: 1}
print dictionary.keys()
print dictionary['alma']
[1, 'alma', 'narancs']
apple

5. Control flow

A. Decision making

In [100]:
x = 3

if x < 3:
    print 'x is smaller than 3'
    
else:
    if x == 3:
        print 'x is equal to 3'
    else:
        if x > 3:
            print 'x is bigger than 3'
x is equal to 3
In [101]:
# A more pythonic way for the conditionals above
x = 4

if x < 3:
    print 'x is smaller than 3'
elif x == 3:
    print 'x is equal to 3'
elif x > 3:
    print 'x is bigger than 3'
x is bigger than 3

B. Loops

for loop

In [102]:
for i in range(3):
    print i
0
1
2
In [103]:
for i in dictionary.keys():
    print i
1
alma
narancs
In [104]:
for k in a_tuple:
    print k
1
2
4
c

while loop

In [105]:
i = 1
print "The value of 'i < 10' statement:", i < 10, '(i=%d)' %i

while i < 10:
    print str(i)+'. neuron'
    i = i + 1

print "The value of 'i < 10' statement:", i < 10, '(i=%d)' %i
The value of 'i < 10' statement: True (i=1)
1. neuron
2. neuron
3. neuron
4. neuron
5. neuron
6. neuron
7. neuron
8. neuron
9. neuron
The value of 'i < 10' statement: False (i=10)

6. Useful modules

To see how to install new modules: https://conda.io/docs/using/pkgs.html

numpy - Mathematical package

In [106]:
import numpy as np
numpy array
In [107]:
lista2 = [2, 3, 4]

tomb = np.array(lista2)  # Making a numpy array from a list

print tomb
print tomb.shape
[2 3 4]
(3,)
In [108]:
tomb2 = np.ones([2, 3])

print tomb2.shape
print tomb2

print np.zeros([2, 6]) # making an array of zeros

print np.eye(2)  # 2x2 unit matrix
(2, 3)
[[ 1.  1.  1.]
 [ 1.  1.  1.]]
[[ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]]
[[ 1.  0.]
 [ 0.  1.]]
In [109]:
a = np.array([2., 3.])
b = np.array([5., 6.])

print ' ', a
print '+', b
print '-------'
print '=', a + b
  [ 2.  3.]
+ [ 5.  6.]
-------
= [ 7.  9.]
In [110]:
print ' ', a, '*', b, '=', a * b
  [ 2.  3.] * [ 5.  6.] = [ 10.  18.]
In [111]:
print ' ', a, '/', b, '=', a / b
  [ 2.  3.] / [ 5.  6.] = [ 0.4  0.5]
In [112]:
x = np.arange(0, 4*np.pi, 0.05)
y = np.sin(x)
z = np.cos(x)

matplotlib - Visualization

In [113]:
import matplotlib.pyplot as plt
%matplotlib nbagg
In [114]:
plt.figure()
plt.plot(x, y)
plt.plot(x, z)
Out[114]:
[<matplotlib.lines.Line2D at 0x7f1445510350>]
In [115]:
# 3D plotting
from mpl_toolkits.mplot3d import Axes3D
In [116]:
n = 1000  # the number of points to generate
points = np.random.rand(n, 3)

plt.figure()
plt.subplot(111, projection='3d')
plt.plot(points[:, 0], points[:, 1], points[:, 2], 'bo')
Out[116]:
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x7f1445199c90>]

7. Defining functions

In [117]:
def f(x):
    print 'hello'
    return x**2
In [118]:
w = f(x)

plt.figure()
plt.plot(x, w)
hello
Out[118]:
[<matplotlib.lines.Line2D at 0x7f144507f590>]
In [ ]: