Python tutorials#

Installation#

  • Anaconda: a comprehensive Python distribution with conda package manager and an array of scietific python packages

Writing and running#

Plain Python files *.py#

Jupyter notebooks *.ipynb#

  • jupyterlab/ jupyter notebook (included in Anaconda dist.)

  • VS Code

Tutorial and reference#

Variable and data types#

  • Assignment (=) : binding a label to an object (data) so you could use it later.

  • Data includes boolean (True/False), numbers (integers, floating-point numbers), text strings, and more.

x = 1
type(x)
int
# String, this is a comment and the Python intepreter will ignore it
greet= "Hello"  # The same as greet= 'Hello'
type(greet)
str
# print function
print(greet, "world", x)
Hello world 1
# Floats
y = 1.0
type(y)
float
# Boolean
type(True)
bool
# Scientific notation
z = 1e-3
z
0.001

Python as a (fancy) calculator#

# + - * / ** % //
# ----------------------------
x = 4
y = 3.0
x + y
7.0
x - y
1.0
x * y
12.0
x / y
1.3333333333333333
x // y
1.0
x ** y
64.0
x % y
1.0
a = 10
a = a + 1
a
11
a = 10
a *= 2
a
20
# Multiple assignments
a, b = 11, 12
print(a, b)
11 12
# swap
b, a = a, b
print(a, b)
12 11

String operations#

# Repeating string
repetition = 10
'abc' * repetition
'abcabcabcabcabcabcabcabcabcabc'
# Concat strings
'a' + 'b'
'ab'
# f-string to insert values to a string (Python 3.6+)
numofcats = 10
f"I have {numofcats} cat(s)."
'I have 10 cat(s).'
x, y = "CAPITAL", 'smol'
x.lower(), y.upper()
('capital', 'SMOL')
'gmail.com'.find('.com')
5
string = 'qwqwqwqwqw'
string[2:5:2]
'qq'

join()#

toJoin = ['This', 'is', 'a', 'string']

# ' '.join(toJoin)
' + '.join(toJoin)
'This + is + a + string'

Containers#

  • List

  • Tuple

  • Dictionary

  • (Set)

List#

# lis = []
# lis = list((2, 3, 4))
# lis

lis = [0, 1, 2, 3]
# lis.append(4)
lis.extend(lis)
lis.insert(0, -1)
lis

lis.remove(1)
lis

lis.count(0)
lis
[-1, 0, 2, 3, 0, 1, 2, 3]
lis = [[1, 1, 1], [2, 2, 2]]
lis[0][0]
1
lis = [0, 1, 2, 3, 2, 3, 5]

# print(sorted(lis))
# print(lis)
# print(lis)
# lis.sort(reverse=True)
# lis.reverse()
# lis
# print(lis)
# a = reversed(lis)
for i in lis:
    print(i)
0
1
2
3
2
3
5

Tuple#

# tuple list str dict set...
# (a, b) = (2, 3)
# a

# a = (2, 3)
# a
# a[1]
# a = ('one', 'two')
# a
# a = (2, 3, 4, 5)
# a
# print(a, len(a))
# a = tuple([1, 1])
# a
# a[1] = 4
lis = [4, 2, 1, 7, 9, 10]

# print(sorted(lis).index(1))

# for i in range(len(lis)):
#     print(i, lis[i])

# for i, v in enumerate(lis):
#     print(i, v)

# 4 in lis

# for i in range(10):
#     if (i in lis):
#         print('Found', i)

# lis[2:]

# lis[:2]

# lis[1:4:2]

lis = []

for i in range(10):
    lis.append(2 * i)
lis


lis = [i for i in range(1, 10) if i % 2 == 0]
lis

# lis = [i ** 2 for i in lis]
# lis
[2, 4, 6, 8]
lis1 = [2, 3, 4]
# sum(lis1)

min(lis1)

# max(lis1)
2
# shallow copy

lis1 = [2, 3, 4]
lis2 = lis1
lis1.append(5)
lis2

# lis1 == lis2
# lis1 is lis2
[2, 3, 4, 5]
# deep copy

import copy

lis1 = [2, 3, 4]
lis2 = copy.deepcopy(lis1)
# lis1.append(5)
lis2

# lis1 == lis2
lis1 is lis2
False

Dictionary#

d = dict()
d = {}

# d[1] = 'one'
# d
# d[2] = 'two'
# d

d = {'one': 1, 'two': 2}
d
d.update({'three': 3, 'two': 5})
d
{'one': 1, 'two': 5, 'three': 3}
# d['Three'] = 10
# d

# del d['three']
# d

# del d['Four']

# print(d.get('Four', 100000000000))
# d.get('Five', 'No such element')
d.setdefault('Five', 5)
d
{'one': 1, 'two': 5, 'three': 3, 'Five': 5}
# for i in d:
#     print(i)

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

# print(list(d.keys()))
# print(d.values())

# for i, j in zip([1, 2, 4], [2, 4, 6]):
#     print(i, j)

for v, k in zip(d.values(), d.keys()):
    print(v, k)
one 1
two 5
three 3
Five 5
1 one
5 two
3 three
5 Five

Set / Frozen Set#

s = set()
# type(s)
s.add(1)
s.add(1)
# s

s.add(10)
s
s.remove(10)
s

# slis = [s, s]
# slis
# lisset = set([10, 9], 10)
# lisset
{1}
geneSet = set([1, 2, 3, 6, 10])
geneSet2 = set([2, 4, 6, 8, 10])
geneSet & geneSet2
# geneSet | geneSet2
# geneSet - geneSet2

geneSet.intersection(geneSet2)
{2, 6, 10}

Logical operators and control flows#

  • Operators: == >= <= != < > and is not or

  • Branching: ifelifelse

  • Loops: for, while

See also: Truth table

2 <= 3
True
2 + 2 == 5
False
'Z' > 'B'
True
# Chaining is possible
1 < 2 < 3
True
4 < 2 < 5
False
(1 > 2) and (1 < 2)
False
not 1 > 2
True
1 > 2 or 1 < 2
True
a = 1
b = 1
a is b
True
a = 1
b = 1.0
a == b
True
a is b
False

if … else#

# if else elif. Note the colon.
if 3 > 5:
    print('Yes! It is true!')
else:
    print('No! It is not true')
    print('Inside of conditional !!!!')
print('Out of conditional')
No! It is not true
Inside of conditional !!!!
Out of conditional
a = 2 ** 3
if a % 2 == 0:
    print('Even')
else:
    print('Odd')
Even
score = 0

print("score =", score)

if score > 100 :
    print('What?')
elif 100 >= score > 80:
    print('Good')
elif 80 >= score > 60: 
    print('Okay')
else :
    print('Oops')
score = 0
Oops

For loops#

for i in range(2, 10):
    print(i, end = ' ')
2 3 4 5 6 7 8 9 
for i in range(10):
    if (i == 3):
        break
    print(i, end = ' ')
0 1 2 

While loops#

# while loop
x = 0
while x < 4:
    print(x)
    x += 1
    if (x == 3):
        break
0
1
2

Useful functions#

# print / input / type conversion / random / math 
# print(10000)
# print('Hello', 'world')
# print('Hello', 'world')
# print('Hello', 'world')
# print('Hello', 'world')
# print('Hello', 'world', sep = ' strange ')
# print('Hello', end = '\t')
print('world', end = '\t')
# print(end = '\n')
print('world')
world	world
type(a)
# type(10)
# int(a) + int (b)
int
# bool(0)
# bool(1)
# int(True)
int(False)
0
# float(10)
int(10.9)
10
import random
random.random()
0.17661514429343628
random.randint(0, 100)
15
random.uniform(0, 100)
35.81805166866937
random.randrange(0, 101, 2)
100
random.choice(['one', 'two', 'three'])
# random.sample((0, 1, 2), 2)
'two'
import math
math.ceil(9.1)
10
math.floor(9.1)
9
10 ** 0.5
3.1622776601683795
math.log(10)
2.302585092994046
math.log10(10)
1.0
math.exp(1)
2.718281828459045
math.pi
3.141592653589793
math.sin(math.pi / 2)
1.0
math.cos(math.pi / 2)
6.123233995736766e-17
math.sqrt(10)
3.1622776601683795

File operations#

  • open()

  • with ... as block