Show Menu
Cheatography

PCAP-31-0x Cheat Sheet (DRAFT) by

Notes for PCAP notification.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Time Module - asctime() and mktime() functions

import time

timestamp = 1572879180
st = time.gmtime(timestamp)

print(time.asctime(st))
print(time.mktime((2019, 11, 4, 14, 53, 0, 0, 308, 0)))

Import Modules

import math
import sys
import math, sys
from math import pi
from math import pi, sin
import math as m
from math import pi as p
from math import pi as PI, sin as sinus

Working with modules

dir()
list all entities within a module

Random Module

from random import seed
seed(a­=None, version=2) - initia­lizes random number generator, a=None current time used
from random import random
random() - random float ranging 0.0<= X < 1.0
from random import randrange
randra­nge­(start, stop[, step])
from random import randint
randint(a, b) - a <= N <= b. Alias for randra­nge(a, b+1)
from random import choice
choice­(seq) - return random element
from random import sample
sample­(po­pul­ation, k, *, counts­=None) - return list of elements

Platform Module

from platform import platform
platfo­rm(­ali­ased=0, terse=0) - returns single stringe showing underlying platform
from platform import machine
machine() - return machine type e. g. 'AMD64'
from platform import processor
proces­sor() - return real processor name 'amdk6'
from platform import system
system() - return OS name e. g. 'Windows', 'Linux'
from platform import version
version() - return system release
from platform import python­_im­ple­men­tation
python­_im­ple­men­tat­ion() - return python version as string 'major.mi­nor.pa­tch­level'

Sorting

sorted()
new list gets created
sort()
performed in situ, changes the original list

OOP - check attributes

class Sampleclass:
    a = 1
    def __init__(self):
        self.b = 2
 
 
object = Sampleclass()
 
print(hasattr(object , 'b'))
print(hasattr(object , 'a'))
print(hasattr(Sampleclass, 'b'))
print(hasattr(Sampleclass, 'a'))

OOP - class variable

class Sampleclass:
    counter = 0
    def __init__(self, var = 1):
        self.__first = var
        Sampleclass.counter += 1

OOP - instance variable

class Sampleclass:
    def __init__(self, var = 1):
        self.first = var

    def set_second(self, var):
        self.second = var

Object Oriented Progra­mming (OOP) - general

class is a set of objects
objects belongs to a class
object is incarn­ation of requir­ements, proper­ties, qualities of a class

OOP - Method Vars

class Sample:
    varia = 2
    def method(self):
        print(self.varia, self.var)


obj = Sample()
obj.var = 3
obj.method()

OOP - Method Resolution Order (MRO)

Way a language scans through the upper part of classes
class Bottom­(Mi­ddle, Top)
works when Top created before Middle
class Bottom­(Top, Middle)
fails when Top created before Middle

OOP - Vars (some)

__dict__
shows entities
__name__
name of class
__module__
name of module
__bases__
names of direct superc­lasses

OOP - Sub/Su­per­class and Incarn­ation

issubc­lass()
identifies relati­onship between 2 classes
 
each class considers itself to be a subclass of itself
isinst­ance()
Checks if object is an incarn­ation of a class

"­Is" operator

checks whether two variables refer to the same object
variables don't store the object, they point to internal Python memory

OOP - Inheri­tance with more than one class

class Sub(Left, Right)
Python scans left to right
 
if vars duplicate, "­Lef­t" vars will be shown

Generators and Iterators - general

Generator produce a series of values and control iteration process (range())
Iterator is an object conforming to iterator protocol (__ite­r__(), __next­__())

Iterator with yield

FAILS
def func(n):
    for i in range(n):
        return i

WORKS
def func(n):
      for i in range(n):
         yield i

List vs Generator

# list generated and iterated through:
for v in [1 if x % 2 == 0 else 0 for x in range(10)]:
    print(v, end=" ")
print()

# subsequent values are generated one by one:
for v in (1 if x % 2 == 0 else 0 for x in range(10)):
    print(v, end=" ")
print()

File streams

read
write
update

File streams open, close, std

open()
open stream
close()
close stream
standard streams with 'import sys'
sys.stdin
 
sys.stdout
 
sys.stderr

File streams continued

'r'
read mode
'w'
write mode
'a'
append mode
'r+'
read and update mode
'w+'
write and update mode
'rt' / 'rb'
read text / binary
'wt' / 'wb'
write text / binary
'at' / 'ab'
append text / binary
'r+t' / 'r+b'
read and update text/b­inary
'w+t' / 'w+b'
write and update text/b­inary

OS Moudle

os.uname()
doesn't work with Windows
os.name()
works with Windows
os.lis­tdir()
print direct­ories
os.mkdir()
create directory
os.mak­edirs()
create multiple direct­ories
os.chdir()
change directory
os.get­cwd()
show current directory
os.rmdir()
delete directory
os.rem­ove­dirs()
removes direct­ories recurs­ively

Datetime Module - Class Date

from datetime import date

v_today = date.today()

print(v_today.year)
print(v_today.month)
print(v_today.day)
print(v_today.today)

###

from datetime import date

d = date(2019, 11, 4)
print(d.weekday())
print(d.isoweekday())

Datetime Module - Class Time

from datetime import time

t = time(14, 53, 20, 1)

print("Time:", t)
print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)
print("Microsecond:", t.microsecond)

Date and time operations

from datetime import date
from datetime import datetime

d1 = date(2020, 11, 4)
d2 = date(2019, 11, 4)

print(d1 - d2)

dt1 = datetime(2020, 11, 4, 0, 0, 0)
dt2 = datetime(2019, 11, 4, 14, 53, 0)

print(dt1 - dt2)

Calendar Module

import calendar

print(calendar.calendar(2023))
calendar.prcal(2023)

Calender for a month

import calendar
print(calendar.month(2020, 11))

Calendar Objects

import calendar  

c = calendar.Calendar(calendar.SUNDAY)

for weekday in c.iterweekdays():
    print(weekday, end=" ")

Calender Create Classes

calend­er.C­al­ender
provides methods for calender data formatting
calend­ar.T­ex­tCa­lendar
create text calendars
calend­ar.H­TM­LCa­lendar
create HTML calendars
calend­ar.L­oc­alT­ext­Cal­endar
subclass (see above) uses local parameter
calend­ar.L­oc­alH­TML­Cal­endar
subclass (see above) uses local parameter

Calender set first week day

import calendar

calendar.setfirstweekday(calendar.SUNDAY)
calendar.prmonth(2020, 12)
 

PIP

pip --version
show pip version (pip version 2)
pip3 --version
show pip version (pip version 3)
pip help
show pip commands
pip help operation
show info about a specific operation
pip show packag­e_name
show info about installed package
pip search string
search for a package
pip install package
package instal­lation

String Operations

ord()
ordinal, code point
chr()
character
possible operations
indexing, iterating, slicing, 'in' and 'not' operators
impossible operations (immut­able)
append, del, insert
max(), min()
uses ASCII value
additional operations
index(), list(), count()

String Methods

capita­lize()
stRiNGdiNg -> stRiNGdiNg
endswi­th(­suf­fix[, start[, end]])
'strin­gdi­ng'.en­dsw­ith­('d­ing') return True
find(sub[, start[, end]])
'strin­gdi­ng'.fi­nd(­'in') return 3 (index #)
isalum()
'string10' -> True, 'strin­g_10' -> False
isalpha()
'string' -> True, 'string10' -> False
isdigit()
'10' -> True, 'string10' -> False
islower()
'strin­gding' -> True, 'strin­GDing' -> False
isspace()
' \n ' -> True, ' ' -> True, 'string ding' -> False
isupper()
'string' -> False, 'stRINg' -> False, 'STRING' -> True
join()
"­,".j­oin­(['li', 'st', 'joined'] -> 'li,st­,jo­ined'
lower()
'stRin­GDing' ->'­str­ing­ding'
lstrip­(str)
'strin­gdi­ng'.ls­tri­p('­str') -> 'ingding'
rstrip­(str)
'strin­gdi­ng'.rs­tri­p('­ding') -> 'str'
replac­e(old, new[, count])
'strin­gdi­ng'.ls­tri­p('­str') -> 'strAn­gdAng'
rfind(­sub[, start[, end]])
'strin­gdi­ng'.rf­ind­('n') -> 8, ('n', 5) -> 8, ('n', 10) -> -1 (failure)
split(str)
'strin­gdi­ng'.sp­lit­('i') -> ['str', 'ngd', 'ng']
starts­wit­h(str)
'strin­gdi­ng'.st­art­swi­th(­'str') -> True, 'strin­gdi­ng'.st­art­swi­th(­'ring') -> False
strip() remove leading, trailing whites­paces
' stringding ' -> 'strin­gding'
swapcase()
'strin­GDiNg' -> 'STRIN­gdInG'
title()
'this Is a title' -> 'This Is A Title'
upper()
'strin­GDiNg' -> 'STRIN­GDING'

String Comparison

Compare
==, !=, <, >, <=, >=
string == number
False
string != umber
True
string >= number
Exception

OOP - Method Invocation

class Sample:
    def other(self):
        print("other")

    def method(self):
        print("method")
        self.other()


obj = Sample()
obj.method()

OOP - Constr­uctor

class Sample:
def __init­__(­self, value = None):
self.var = value


obj_1 = Sample­("ob­jec­t")
obj_2 = Sample()

print(­obj­_1.var)
print(­obj­_2.var)

OOP - Hiding

class Sample:
def visibl­e(s­elf):
print(­"­vis­ibl­e")

def __hidd­en(­self):
print(­"­hid­den­")


obj = Sample()
obj.vi­sible()

try:
obj.__­hid­den()
except:
print(­"­fai­led­")

obj._S­amp­le_­_hi­dden()

Exception continued

try:
   this is what we want
except:
   this is what we do with errors
else:
   we do this when no exception has been raised and our "try" was successful
final:
   no matter of what the outcome is we do that

Exceptions are classes

try:
    raise Exception
except Exception as e:
    print(e, e.__str__(), e.args)

Lambda

lambda parameter: expression
lambda x: x * 2
 
lambda x, y: x * y
 
lambda x, y, z: (x * y) / z

map() function

map(arg1, arg2)
list = list(m­ap(­lambda x: x * 2, source­list))
arg1
a function what to do
arg2
iterable object (list, tuple, generator, ...)

filter() function

filter items based on a given statement
filter­(arg1, arg2)
list = list(f­ilt­er(­lambda x: x > 2, source­list))
arg1
function to what to filter
arg2
iterable object (list, tuple, generator, ...)

Condit­ional Expression

print(True if 0 ≥ 0 else False)

Work with files

read(1)
read chars -> 1 byte chunks
read()
read chars all at once
readli­ne(10)
read lines -> 10 byte chunks
readline()
read full line
readli­nes(10)
read all lines -> 10 byte size chunks
readli­nes()
read all lines
write(­arg1)
write to a file

Bytearray

data = bytear­ray(10)
creates a bytearray filled with 0's
 
are mutable, len(), index()
 
only integers, only 0 to 255

Bytearray - write to binary file

from os import strerror

data = bytearray(10)

for i in range(len(data)):
    data[i] = 10 + i

try:
    bf = open('file.bin', 'wb')
    bf.write(data)
    bf.close()
except IOError as e:
    print("I/O error occurred:", strerror(e.errno))

Bytearray - read from binary file

from os import strerror

data = bytearray(10)

try:
    binary_file = open('file.bin', 'rb')
    binary_file.readinto(data) # file.read(data) would also work
    binary_file.close()

    for b in data:
        print(hex(b), end=' ')
except IOError as e:
    print("I/O error occurred:", strerror(e.errno))

Time Module

import time

timestamp = 1572879180
print(time.ctime(timestamp))
print(time.gmtime(timestamp))
print(time.localtime(timestamp))

print(time.ctime())

timest­amp()

from datetime import datetime

dt = datetime(2020, 10, 4, 14, 55)
print("Timestamp:", dt.timestamp())

strftime()

from datetime import time
from datetime import datetime

t = time(14, 53)
print(t.strftime("%H:%M:%S"))

dt = datetime(2020, 11, 4, 14, 53)
print(dt.strftime("%y/%B/%d %H:%M:%S"))

stftime() in Time Module

import time

timestamp = 1572879180
st = time.gmtime(timestamp)

print(time.strftime("%Y/%m/%d %H:%M:%S", st))
print(time.strftime("%Y/%m/%d %H:%M:%S"))

timede­lta()

from datetime import timedelta
 
delta = timedelta(weeks=2, days=2, hours=3)
print(delta)
print("Days:", delta.days)
print("Seconds:", delta.seconds)
print("Microseconds:", delta.microseconds)

###

from datetime import timedelta
from datetime import date
from datetime import datetime

delta = timedelta(weeks=2, days=2, hours=2)
print(delta)

delta2 = delta * 2
print(delta2)

d = date(2019, 10, 4) + delta2
print(d)

dt = datetime(2019, 10, 4, 14, 53) + delta2
print(dt)

Calender Iterators

itermo­nth­dates()
returns days of the week as int
itermo­nth­dat­es2()
return tuple day of the month int and week day int
itermo­nth­days3()
return days as tuple year int, month int, day of month int
itermo­nth­days4()
return days as tuple with year int, month int day of month int, day of week int

Leap Year

isleap­(<y­ear­>)
Check is year specified is leap year
leapda­ys(­<year1, year2>)
returns number of lead years in specified range

Calender weekday()

import calendar
print(calendar.weekday(2020, 12, 24))