Link Search Menu Expand Document


Table of contents

  1. Setup
  2. Organization
    1. General
      1. Naming Convention
      2. Numbers
      3. Decimal
      4. Text
    2. List
      1. Access
      2. Work with List
      3. Search
    3. Dictionnary
      1. Single dimension
      2. Multiple dimensions
    4. Tuples
    5. Thread-based parallelism
    6. Modules management
  3. Loops
    1. If
    2. While
    3. For
    4. Switch
    5. Try
  4. Functions
    1. Text
      1. Retrieve
      2. Transformations
      3. Base conversion (decimal, hexadecimal, binary)
    2. Numbers
    3. Bytearrays
    4. Files
    5. Logs - Logging class
    6. Network
      1. Requests: PUT, GET, POST
      2. UDP Communication
  5. Classes & Objects
    1. Definition
    2. Usage
    3. Inheritance
  6. XML
    1. Structure
    2. In Python
  7. JSON
  8. Development
    1. Package application
    2. Publish an application on PyPI


  • PC: check Python website
  • Raspberry Pi OS: sudo apt install python3-pip for Python 3



Text Action
# Comment, sinlge line
``` Comment, multiple lines
var x Declare a new var, any type
var _x Private variable
x = name.fctA(par) Populate var x with the function
from math import * Import every module from math

Naming Convention

See here


  • 123 is integer
  • 123.0 is float


  • Integer to Decimal: bin(int) but remove leading 0
  • Advanced: use format() - documentation
    • Example: format(14, '#010b') to output '0b00001110'
    • The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits. (Source)
  • How to manage bitmasks = work with one bit - Source
    • Get a bit by shifting everything to the right
        def get_normalized_bit(value, bit_index):
            return (value >> bit_index) & 1


Text Action
print(x) Print text in x
print(x, end =",") Print text in x and finish by “,”
"x\nhey" or "x\hey" new line between x and hey
Link Escape characters list


Text Action
list = [a, b, c] Declare a list “list” with variables a b c, can be any type
list = [[a,b][c,d] List in list
print(*list, sep=", ") print each item in list with , as separator


Text Action
list[0] access item 0 (is “a”)
list[-1] access last item (is “c”)
list[0:1] sub-list from 0 to 1

Work with List

Text Action
list.extend(list2) add list2 after list -> list, list2
list.append(list2) add list2 as sub-list in list -> list, [list2]
list.insert(position, item) insert
list.remove(item) remove
list.clear() remove all items
list.pop() remove last item
list.copy() copy item
list.sort() sort the list by a-z, 0-9
list.reverse() inverse of sort
Text Action
list.index(name) search in list for “name”
list.count(item) count items


Key:Value pairs

Single dimension

Text Action
dict = {key:work, k1:w1} declare
dict['key'] or dict.get('key') get
dict.get('key', "default value") get with fallback

Multiple dimensions

Text Action
dict = { k1:{k11:w, k12:w},
k2:{k21:w, k22:w}}
dict[0][1] -> k12


Like List but immutable

  • x = (4, 5)
  • x = ([1,2],[3,4])

Thread-based parallelism

The following function will return “Spun off” before “Done”, as there’s a wait function. Source

import threading, time

def my_threaded_func(arg):
    print("Running thread! Args:", (arg))

thread = threading.Thread(target=my_threaded_func, args=("I'm a thread",))
# Note the ,) at the end: Thread expect arg to be iterable, so you have to pass a tuple
print("Spun off thread")

Modules management

  • pip install x
  • pip uninstall x


Operators: <,<=, ==, !=, =>, >


var = Trues
if var:
    if char in text:
        do things
    elif var1 or not(var2) or var3 > var 4:
        do things
   do thing


i = 1
while i<10:


Good for index!

for item in items:          # Go through all items
    do something with item  # item is one of the items
    break                   # Break the current loop
for item in [a, b]:         # same with 2 items
for item in string:         # same with string - treat is char


Does not exist in Python, so needs to use If.


    do things
except ValueError:
    do things               # If ValueError is raised
except ValueError as err:
    print(err)              # print err being the rrror
    do things               # If any error is raised


# Know the type of the variable (float, int, str, list, dict, tuple)
x = isinstance(var, str) # x = True if var:str


Is an index


a = input("str")            # Ask for input with message "str", put in a


x.index("a")                # return start index of string/char
x.replace("old", "new")     # replace in x "old" by "new"

Base conversion (decimal, hexadecimal, binary)

import binascii
y = binascii.hexlify(x)     # convert x in hexadecimal


Text Action
str(x) int to str
int(x) or float(x) str to int or float


[hex(i) for i in data]  # print content of data in pretty hexadecimal


Text Action
a = open("f.txt", "r+") open the file in:
r+ - read & write>
r - read
w - write
a - append
a.close() close
a.readable() bool to check if Read possible
a.readlines() read each lines in array [line1, lineN]
a.write("text") Mode “w”: overwrite the file with text
Mode “a”: append text at end of file

Logs - Logging class

Example inspired from this StackOverflow thread

_log_format = logging.Formatter('[%(asctime)s] [%(levelname)s] - %(message)s')
_LOGGER = logging.getLogger(__name__)                                  

# writing to stdout                                                     
handler = logging.StreamHandler(sys.stdout)                             
_LOGGER.debug("Logging has been setup")   


Requests: PUT, GET, POST

Example of a POST:

import requests
user = "user"
pwd = "password"
headers = {"Content-Type":"application/json"}
data_JSON = {
    "id": "value",
response =, auth=(user, pwd), headers=headers, json=data_JSON)

You can use data= instead of json=.

UDP Communication

Text Action
import socket  
UDPServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) Initiate a new UDP socket
To receive something  
UDPServerSocket.bind(("", port)) Bind the socket to port
data, address = UDPServerSocket.recvfrom(1024) Receive incoming data and ip with a buffer size of 1024
To send something  
UDPServerSocket.sendto(data, (host, port)) Send data to host:port


Classes & Objects


class ClassName:	
    def __init__(self, a, b):   # a b are used for initialization
        self.a  = a
        self.a  = a
    def function(self):	
        return a
    def functionb(self, x: int) # x must be of type int
        return x


from filename import ClassName
object = ClassName("a", "b")

# Delete an object
del object


from filename import ClassName

class Child(Parent):

    def fct(self):
        do things

    def overridenFct(self):
        do things



<tag>Text content</tag>
<tag attribute1="something1 something2"/>

In Python

Text Action
data.find('key').text get the Text content
data.find('key').get('attribute1') get the Attribute content


import json	
data = "{ 'k1': 'w1' }"         # JSON string
dictData = json.loads(data)     # load a JSON string in dictData
print(dictData['k1'])           # print content of k1
data['k1'].get['k12','']        # Get [k1][k12], otherwise return ''


Package application


  1. Create the structure
     └── src/
         └── example_pkg/
  2. Configure metadata
     # replace with your username:
     name = example-pkg-YOUR-USERNAME-HERE
     version = 0.0.1
     author = Example Author
     author_email =
     description = A small example package
     long_description = file:
     long_description_content_type = text/markdown
     url =
     project_urls =
         Bug Tracker =
     classifiers =
         Programming Language :: Python :: 3
         License :: OSI Approved :: MIT License
         Operating System :: OS Independent
     package_dir =
         = src
     packages = find:
     python_requires = >=3.6
     where = src
  3. Create README
  4. Create LICENSE
  5. Update if necessary
    • Windows py -m pip install --upgrade build
    • Unix python3 -m pip install --upgrade build
  6. Generate
    • Windows py -m build
    • Unix python3 -m build
  7. Install pip install C:/some-dir/some-file.whl

To use this example: from example_pkg import example_pkg

Publish an application on PyPI

There’s a good tutorial here

  1. Configure
  2. Document with Readme and License
  3. Increment version in and
    • Or with bump2version --current-version 1.0.0 minor PROJECT/
  4. Install pip install twine wheel if necessary
  5. Create archive and wheel python sdist bdist_wheel
  6. Check twine check dist/*
  7. Upload to TestPyPI twine upload --repository-url dist/*
  8. Upload to PyPi twine upload dist/*
  9. Make a release in GitHub