Python tutorials

Installation

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

Writing and running

Plain Python files *.py

Jupyter notebooks *.ipynb

  • Jupyterlab/ Jupiter 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)
0.1s
Python
# String, this is a comment and the Python intepreter will ignore it
greet= "Hello"  # The same as greet= 'Hello'
type(greet)
0.0s
Python
# print function
print(greet, "world", x)
0.4s
Python
Hello world 1
# Floats
y = 1.0
type(y)
0.0s
Python
# Boolean
type(True)
0.0s
Python
# Scientific notation
z = 1e-3
z
0.0s
Python

Python as a (fancy) calculator

# + - * / ** % //
# ----------------------------
x = 4
y = 3.0
0.0s
Python
x + y
0.0s
Python
x - y
0.0s
Python
x * y
0.0s
Python
x / y
0.0s
Python
x // y
0.0s
Python
x ** y
0.0s
Python
x % y
0.0s
Python
a = 10
a = a + 1
a
0.0s
Python
a = 10
a *= 2
a
0.0s
Python
# Multiple assignments
a, b = 11, 12
print(a, b)
0.3s
Python
11 12
# swap
b, a = a, b
print(a, b)
0.3s
Python
12 11

String operations

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

join()

toJoin = ['This', 'is', 'a', 'string']
# ' '.join(toJoin)
' + '.join(toJoin)
0.0s
Python

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
0.0s
Python
lis = [[1, 1, 1], [2, 2, 2]]
lis[0][0]
0.0s
Python

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.3s
Python
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
0.0s
Python
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
0.0s
Python
lis1 = [2, 3, 4]
# sum(lis1)
min(lis1)
# max(lis1)
0.0s
Python
# shallow copy
lis1 = [2, 3, 4]
lis2 = lis1
lis1.append(5)
lis2
# lis1 == lis2
# lis1 is lis2
0.0s
Python
# deep copy
import copy
lis1 = [2, 3, 4]
lis2 = copy.deepcopy(lis1)
# lis1.append(5)
lis2
# lis1 == lis2
lis1 is lis2
0.0s
Python

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
0.0s
Python
# 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
0.0s
Python
# 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)
0.3s
Python
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
0.0s
Python
geneSet = set([1, 2, 3, 6, 10])
geneSet2 = set([2, 4, 6, 8, 10])
geneSet & geneSet2
# geneSet | geneSet2
# geneSet - geneSet2
geneSet.intersection(geneSet2)
0.0s
Python

Logical operators and control flows

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

  • Branching: if ... elif...else

  • Loops: for, while

See also: Truth table

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

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')
0.4s
Python
No! It is not true Inside of conditional !!!! Out of conditional
a = 2 ** 3
if a % 2 == 0:
    print('Even')
else:
    print('Odd')
0.3s
Python
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')
0.3s
Python
score = 0 Oops

For loops

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

While loops

# while loop
x = 0
while x < 4:
    print(x)
    x += 1
    if (x == 3):
        break
0.3s
Python
0 1 2
x = input('input a number')
while True:
    print(x)
    x = input('input a number')
    if x == '-1':
        break
0.2s
Python
input a number 111 111 input a number 111 111 input a number -1

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')
0.3s
Python
world world
type(a)
# type(10)
# int(a) + int (b)
0.0s
Python
# bool(0)
# bool(1)
# int(True)
int(False)
0.0s
Python
# float(10)
int(10.9)
0.0s
Python
import random
0.0s
Python
random.random()
0.1s
Python
random.randint(0, 100)
0.0s
Python
random.uniform(0, 100)
0.0s
Python
random.randrange(0, 101, 2)
0.0s
Python
random.choice(['one', 'two', 'three'])
# random.sample((0, 1, 2), 2)
0.0s
Python
import math
0.0s
Python
math.ceil(9.1)
0.0s
Python
math.floor(9.1)
0.0s
Python
10 ** 0.5
0.0s
Python
math.log(10)
0.0s
Python
math.log10(10)
0.0s
Python
math.exp(1)
0.0s
Python
math.pi
0.0s
Python
math.sin(math.pi / 2)
0.0s
Python
math.cos(math.pi / 2)
0.0s
Python
math.sqrt(10)
0.0s
Python

File operations

  • open()

  • with ... as block

Runtimes (1)