Python tutorial

built-in functions

  • print
  • type
  • dir

built-in data types

  • int
  • float
  • str
  • bool

  • list

  • tuple
  • set
  • dict

In [1]:
# Basic python
print("Hello world!")

print(type("Hello world!"))

print(type("Hello world!")==str)

# dir()


Hello world!
<class 'str'>
True

In [2]:
# Built-in data types

# int
print(type(1))

# float
print(type(1.0))

# str
print(type("Hello World"))

# bool
print(type(False))


<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

In [3]:
# Built-in data types: list

alist = [1, 2.0, "3"]
print(alist)
print(type(alist))
print(len(alist))

alist.append(4)
print(alist)


[1, 2.0, '3']
<class 'list'>
3
[1, 2.0, '3', 4]

In [4]:
# how to access elements in a list

print(alist)
print(alist[1])
print(alist[::3])
print(alist[1:])
print(alist[:-1])


[1, 2.0, '3', 4]
2.0
[1, 4]
[2.0, '3', 4]
[1, 2.0, '3']

In [5]:
# Built-in data types: tuple

atuple = (1, 2.0, "3")
print(atuple)
print(type(atuple))

# how to accesse elements in a list
print(atuple[1])
print(atuple[::2])
print(atuple[1:])
print(atuple[:-1])


(1, 2.0, '3')
<class 'tuple'>
2.0
(1, '3')
(2.0, '3')
(1, 2.0)

In [6]:
# Set & dictionary

aset = {1, 2.0, '3'}
print(aset)

adict = {1:"1.000", 2.0:"2.000", "3":"3.000"}
print(adict)
print(adict[1])
print(adict.keys(), adict.values())


{1, 2.0, '3'}
{1: '1.000', 2.0: '2.000', '3': '3.000'}
1.000
dict_keys([1, 2.0, '3']) dict_values(['1.000', '2.000', '3.000'])

Control flow commands


In [7]:
# for

for i in range(10):
    print(i)


0
1
2
3
4
5
6
7
8
9

In [8]:
# for

print(alist)

for _ in alist:
    print(_)


[1, 2.0, '3', 4]
1
2.0
3
4

In [9]:
# for

print(adict)

for k, v in adict.items():
    print(k, v)


{1: '1.000', 2.0: '2.000', '3': '3.000'}
1 1.000
2.0 2.000
3 3.000

In [10]:
# if elif else

data = [-2, 0, 2]

for _ in data:
    if _ < 0:
        print(_)
    elif _ == 0:
        print("exactly 0")
    else:
        print(_)


-2
exactly 0
2

In [11]:
# while

a = 10
while(a>0):
    print(a) 
    a-=3


10
7
4
1

numpy


In [12]:
# how to import packages/modules

# 1
import numpy
print(numpy.sqrt(2))

# 2
import numpy as np
print(np.sqrt(2))

# 3
from numpy import sqrt
print(sqrt(2))


1.41421356237
1.41421356237
1.41421356237

In [13]:
# numpy.ndarray VS list

x_list = [1,2,3]

import numpy as np
x_array = np.array(x_list)

print(x_list, x_list*2)
print(x_array, x_array*2)


[1, 2, 3] [1, 2, 3, 1, 2, 3]
[1 2 3] [2 4 6]

In [14]:
# numpy

import numpy as np
a = np.arange(15).reshape(3, 5)
print("a = ", a)

print("the shape of a is ", a.shape)

print(a.ndim)

print(a.dtype.name)

print(a.itemsize)

print(a.size)

print(type(a))


a =  [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
the shape of a is  (3, 5)
2
int64
8
15
<class 'numpy.ndarray'>

matplotlib


In [18]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams.update({'font.size':20})

fig = plt.figure(figsize=(10,10))
x = np.linspace(0, 6*np.pi, 100)
plt.plot(x, np.cos(x), 'r');
plt.plot(x, np.sin(x), 'b-');

# legend?



In [16]:
%pylab inline
rcParams.update({'font.size':20})

n_mc = 10000
x = np.random.rand(n_mc,)
y = np.random.rand(n_mc,)
theta = np.linspace(0., 0.5*np.pi, 100)
cx = np.cos(theta)
cy = np.sin(theta)
pi_est = 4.0*np.sum((x**2+y**2)<1.)/n_mc

fig = figure(figsize=(8,8))
ax = fig.add_subplot(111)
line, = plot(x, y, '.')
c, = plot(cx, cy, 'r-')
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("estimated pi = {:.10f}".format(pi_est));


Populating the interactive namespace from numpy and matplotlib

In [17]:
print(1)


1

In [ ]:


In [ ]:


In [ ]: