Basic

Data Type

int

  • Decimal: 0, 100, -8080, ...
  • Hexadecimal, start with 0x, range 0-9, a-f: 0xff00

Python allows use _ to separate numbers, 100_00 == 10000

Some notes:

  1. / can transform int to float. For example: 3 / 2 = 1.5

  2. // is equal to floor(). The result is int.

  3. int() and floor() are different.

    int(3 // 2) # 1
    3 // 2 # 1
    
    int(-3 // 2) # -1
    -3 // 2 # -2
    

float

1.23, 1.23e5 (1.23 * 10 ^ 5)

int is percise and float is not. It depends on how they are stored on the computer.

boolean

True or False

we can use and, or, not to do boolean calcul.

None

None is special value in Python, means none.

string

'' and "" are the same.

\ can translate the meaning.

""" """ is for multi lines.

To format the string, there are 3 ways:

  • "My name is %s. I'am %d years old" % ("Jack", 10)

    %s: string, %d: int, %f: float, %x: hex

    %% inputs "%"

  • f-string:

    name = "Jack"
    age = 10
    print(f"My name is {name}. I'am {age} years old");
    
  • "My name is {0}. I'am %d years {1}".format("Jack", 10)

JSON and string:

  • json.dump(): basic types => string

  • json.loads(): string => basic types

list vs tuple

  • list: a mutable ordered set contains any type of data.
  • tuple: a immutable ordered set contains any type of data.

Some operation:

l = [1, 2, 3, 4]

  • get last element: list[-1] # 4

  • slice: list[1:3] # 2, 3

    list = [1, 2, 3]
    tuple = (4, 5, 6)
    
    print(list[1:2]) # 2 3
    print(list[::2]) # step = 2, output: 1 3
    print(tuple[-1]) # 6
    
  • embed:

    t = ('a', 'b', l)
    t[2][0] = 0
    print(t) # ('a', 'b', [0, 2, 3, 4])
    

    list in the tuple is still mutable

  • list(t) or tuple(l)

  • some function:

    count(item)
    index(item)
    l.reverse() / l.sort() # apply on variable l directly, so that it's ONLY FOR the list
    

usage

Tuple is immutable. It hasn't pointers. So that, it's lighter than list.

Tuple is perfect for static data, such as cache, const data, etc.

dict and set

  • dict: A hash map used to stock key - value paires.

  • set: A hash map store ONLY the key

Both of them are based on hash map. Hash value is generated by key.

Note: key must be immutable, such as string

So that dict and set is built for search.

  • dict:

    d = {'name': 'Jack', 'age': 10}
    print(d['name']) # Jack
    

    To check key in dict:

    # method 1: in
    
    print('name' in d) #  True
    
    # method 2: get()
    
    d.get('age') # 10
    d.get('major') # None
    d.get('gender', -1) # -1
    

    remove an element

    d.pop('name')
    

    d.pop() can be dangerous. Hash map hasn't an order.

  • set:

    # It needs a list to init a set
    s = set([1, 2, 3])
    

    some operation: add, remove:

    s.add(4)
    s.remove(1)
    

    Note: set can use index to search because hash map isn't ordered.

usage

dict and set are both for search. dict is more useful for managing items, while set is more suitbale for managing conditions, such as 'Jack' in student_set.

condition

if


if condition_1:
    statement_1
elif condition_2:
    statement_2
...
elif condition_i:
    statement_i
else:
    statement_n

for

for item in <iterable>:
    ...

For dict:


d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}
for key in d: 
    print(key)

# name dob gender

for value in d.values():
    print(value)

# jason 2000-01-01 male    

for key, value in d.items(): 
    print('key: {}, value: {}'.format(key, value))

# key: name, value: jason key: dob, value: 2000-01-01 key: gender, value: male 

For list:

l = ["a", "b", "c"]
for item in l:
    print(item)

# a b c

for index, item in enumerate(l): 
    print('i: {}, item: {}'.format(index, item))

# i:0, item: a i:1, item: b i:2, item: c

simple expressions

  • expression for item in iterable if condition

    equl to:

    for item in iterable:
        if condition:
            expression
    

    example:

    l = [s.strip() for s in text.split(',') if len(s.strip()) > 3]
    
  • expression1 if condition else expression2 for item in iterable

    equl to:

    for item in iterable:
        if condition:
            expression1
        else:
            expression2
    
    y = [value * 2 + 5 if value > 0 else -value * 2 + 5 for value in x]
    
  • [(xx, yy) for xx in x for yy in y if xx != yy]

    equl to:

    l = []
    for xx in x:
        for yy in y:
            if xx != yy:
                l.append((xx, yy))
    

Error

Some codes will meet errors, such as connecting Database, fetching data from APIs, etc. We need to use try ... except ... to catch errors.

try:
    ...
except ValueError as err:
    # ONLY catch ValueError
    print('Value Error: {}'.format(err))
except IndexError as err:
    # ONLY catch IndexError
    print('Index Error: {}'.format(err))
except Exception as err:
    # catch all kinds of error
    print('Other error: {}'.format(err))

try ... except ... finally is also very common. The codes in finally will run even we meet errors.

import sys
try:
    f = open('file.txt', 'r')
    .... # some data processing
except OSError as err:
    print('OS error: {}'.format(err))
except:
    print('Unexpected error:', sys.exc_info()[0])
finally:
    f.close()

Module

.
├── utils
│   ├── utils.py
│   └── class_utils.py
├── src
│   └── sub_main.py
└── main.py
# utils/utils.py

def get_sum(a, b):
    return a + b
# utils/class_utils.py

class Encoder(object):
    def encode(self, s):
        return s[::-1]

class Decoder(object):
    def decode(self, s):
        return ''.join(reversed(list(s)))
# src/main.py

from proto.mat import Matrix
from utils.mat_mul import mat_mul


a = Matrix([[1, 2], [3, 4]])
b = Matrix([[5, 6], [7, 8]])

print(mat_mul(a, b).data)

########## output ##########

[[19, 22], [43, 50]]

Python use from ... import ... to import module.

Python can export class or function.

Python replaces / by . in the path of import.

The best practice to set path is:

  1. use absolute path

  2. set the path root in python virtual environment.

    • always change an isolated env for each project

    • add project root into activate file

      export PYTHONPATH="/home/ubuntu/workspace/your_projects"
      

To test a module, we can use if __name__ == "__main__"

# my-code.py

def my_code:
    pass

if __name__ == "__main__":
    my_code() 

Now, we can run my-code.py in the console: python my-code.py