[String]
❑ ‘py’ ‘thon’ → ‘python’
❑ ‘py’*3 → ‘pypypy’
❑ ‘python’[0] → ‘p’
*Indexing : Selecting one element.
❑ ‘python’[1:4] → ‘yth’
❑ ‘python’[-2:] → ‘on’
* Slicing : Selecting several element.
❑ “str=124”.split(“=”) → ['str', '124']
❑ "abcd".upper() → "ABCD"
❑ "ABCD".lower() → "abcd"
❑ str1 = raw_input("Input : ") : Input the user's string in string type.
❑ str1 = input("Input : ") : User's string is inputted in string type in Python 3.x but it has more wide meaning in Python 2.x. It should be careful.
[Dictionary]
It is a data structure consisting of pairs of a key and a value.
❑ d = {} → {}
❑ d = dict(a=1, b=3, c=5) → {‘a’:1, ‘c’:5, ‘b’:3}
❑ d[‘f’] → "This is f" : Print the value of the key "f".
❑ d[‘f’] = “This is f” : Input a value in key "f".
❑ if d.get(“f”) == None: ~~ : Check if there is a value corresponding the key 'f'.
* If there is no corresponding value for the key, the dic["key"] causes an error but dic.get("key") does not.
❑ d.items() : Group all keys and values into tuple and return it as dict_items object.
❑ d.keys() : Return all keys as dict_keys object.
* list(d.keys()) : Return all keys as list.
❑ d.values() : Return all vales as dict_values object.
❑ del d[‘a’] : Remove a registered value with 'a' key.
❑ d.clear() : Remove all keys and values.
❑ abc = d.copy() : Copy the dictionary 'd' and assign it.
* When assign without a copy, the reference value is passed. So when the contents of 'd' are modified, 'abc' is also modified.
❑ if not d: ~~ : Check if the dictionary is empty.
[List]
In Python, list can be used like arrays, but pure array doesn't exist.
❑ colors = [‘red’, ‘green’, ‘gold’]
❑ colorColors = [[‘red’, ‘green’, ‘gold’], [‘blue’, ‘yellow’, ‘brown’], [‘black’, ‘orange’, ‘silver’]]
❑ colors.append(‘blue’) : Append the value 'blue' at the end.
❑ colors.insert(1, ‘black’) : Insert 'black' string at position 1. Existing values are moved to the next positions.
❑ colors.extend([‘white’, ‘gray’]) : Append multiple values at the end.
❑ colors.index(‘red’) → 0 : Return the index of the input value 'red'.
❑ colors.count(‘red’) → 1 : Count the number of input value 'red'.
❑ colors.extend(abc) : Append all the contents of the list 'abc' to the 'colors' list.
❑ colors = abc[:] : Assign all values of copyied "abc" to "color".
* When assign without a copy, the reference value is passed. So when the contents of "colors" are modified, "abc" is also modified.
❑ colors.pop() → ‘gold’
❑ del colors[:] : Remove all data in the list.
❑ “red” in colors → True : Search a value in the list.
❑ colors.remove("red") : Remove a first searched value.
❑ colors.sort() → ['gold', 'green', 'red'] : Sort in ascending order.
❑ colorColors.sort(key=lambda x: x[1]) → [['red', 'green', 'gold'], ['black', 'orange', 'silver'], ['blue', 'yellow', 'brown']] : Sort in ascending order based on the second element.
❑ colors.reverse() → ['gold', 'green', 'red'] : Reverse the order with no return value.
❑ list(reversed(colors)) → ['gold', 'green', 'red'] : Reverse the order with return of list.
❑ arr[2:7:-1] : Make the reverse order from 2 to 6(Extended slices)
❑ arr = [0]*20 : Initialize a list with "0".
❑ Built in list : How to create a new list.
t = [“orange”, “apple”, “banana”]
>>> [len(i) for i in t] → [6, 5, 6]
>>> [i for i in t if len(i)>5] → [‘orange’, banana’]
>>> [x*y for x in L_1 for y in L_2] → Cartesian product
>>> [len(i) for i in t] → [6, 5, 6]
>>> [i for i in t if len(i)>5] → [‘orange’, banana’]
>>> [x*y for x in L_1 for y in L_2] → Cartesian product
❑ list(t) : Change other types, such as tuples and sets, to list types.
❑ "".join(colors) → "redgreengold" : Make the list the string.
❑ ":".join(colors) → "red:green:gold" : Make the list the string including the delimiter character.
❑ list1 = [x for x in range(0, 10)] → [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: List comprehension. Initialize the list.
❑ list1 = [None] * 3 → [None, None, None]: Initialize the list with None.
[Tuple]
Read-only list using ().
❑ tup1 = (1,2,3) : Packing.
❑ tup1 = 1,2,3 : Packing.
❑ a,b,c = tup1 → a=1, b=2, c=3 : Unpacking.
❑ tup1[0] → 1
[Set]
It is the same as the set of mathematics
(A collection of unordered values)
❑ Set does not allow duplicates.
❑ a={1, 2, 3} b={3, 4, 5}
❑ a & b → {3} : &(Intersection), |(Union), -(Difference)
❑ a.add(4) → {1,2,3,4}
❑ a.update([4,5,6]) → {1,2,3,4,5,6}
❑ a.remove(3) → {1,2}
[Function]
❑ When a function is declared, a function object and a reference pointing to the function object are created.
❑ Function usage is possible through the reference.
❑ The arguments of the function are passed through the reference.
❑ Scoping rule is LGB(Local → Global → Built-in order).
* Scoping rule : It is a rule that determine the namespace search order when using variables.
❑ Basic argument : Pre-assign a value to the argument.
def Times(a=10, b=20):
return a*b
>>> Times() → 100
return a*b
>>> Times() → 100
❑ Keyword argument : Pass arguments by specifying the parameter name.
>>> Times(b=10, a=20)
❑ Variable argument : Pass arguments as tuples.
def union2(*var1):
>>> union2((“HAM”, “EGG”, “SAPM”))
>>> union2((“HAM”, “EGG”, “SAPM”))
❑ Undefined argument : Pass arguments as dictionary.
def union2(**var1):
❑ Lambda : An unnamed one-line function.
g = lambda x, y : x+y
>>> g(3, 4) → 7
>>> (lambda x : x*x)(3) → 9
>>> g(3, 4) → 7
>>> (lambda x : x*x)(3) → 9
❑ Generator : Unlike a function, It uses "yield" not "return" to return an object.
[Class]
❑ Information hiding : Specifying data and methods used only within a class.
❑ Abstraction : Writing the common parts of classes(children) as separate classes(parent classes).
❑ Classes can be used after creating an instance object.
* class Persion: → Class definition p1 = Persion() → Instance object create
❑ Adding additional members to the instance object after class definition is possible.
* p1.age = 20 p1.gender = ‘m’
❑ isinstance(p, pp) → True/False : Check whether object "p" is an instance of "pp" class.
❑ issubclass(Child class, Parent class) : Check class inheritance.
❑ Constructor performs initialization when instance creation : __init__():
❑ Destructor performs exit operations when instance remove(It is called when the reference counter of the instance object becomes 0) : __del__():
❑ Static method : A method that calls directly through a class, rather than through an instance object.
❑ Class method : A methods that access data in the class region directly.
❑ Inheritance : Pass all the properties(data, methods) of the parent class to child classes.
* General inheritance : class Student(Person)
* Multiple inheritance : class Student(Person, school))
[Control statement]
It is divided into loop statement and condition statement.
❑ if
if score >= 50 & score < 60:
print(“abc”)
elif ~:
print(“123”)
else:
print(“234”)
print(“abc”)
elif ~:
print(“123”)
else:
print(“234”)
❑ while
while value > 0:
print(value)
value=value-1
print(value)
value=value-1
❑ for
sequence = [‘a’, ‘b’, ‘c’]
* sequence : String, List, Tuple, Dictionary, Iterater, Generator is available.
for item in sequence:
print(item)
else: ~~ * The else block is executed if it doesn't break in the middle.
for num, item in enumerate(sequence):
* "num" stores the number of times that loop was repeated.
* "item" stores a content of "sequence".
* sequence : String, List, Tuple, Dictionary, Iterater, Generator is available.
for item in sequence:
print(item)
else: ~~ * The else block is executed if it doesn't break in the middle.
for num, item in enumerate(sequence):
* "num" stores the number of times that loop was repeated.
* "item" stores a content of "sequence".
❑ Break : leaves the loop block.
❑ Continue : goes to beginning of the loop block with the selected next item.
[Bitwise operator]
It is the operator that calculates by bit.
It is the operator that calculates by bit.
❑ AND(&): (1 & 1 == 1), (1 & 0 == 0), (0 & 0 == 0)
❑ OR(|): (1 | 1 == 1), (1 | 0 == 1), (0 | 0 == 0)
❑ XOR(^): (1 ^ 1 == 0), (1 ^ 0 == 1), (0 ^ 0 == 0)
❑ NOT(~): (~1 == 0), (~0 == 1)
❑ SHIFT(<<, >>): (0b10110<<2 == 0b1011000), (0b10110>>2 == 0b101)
[Module]
It is the collection of codes that can be reused elsewhere.
❑ import [Module] : Import modules into the current namespace.
* The module name becomes an object like "math.pow(2, 10)".
❑ from [Module] import [Attribute] : Import modules's attributes into the current namespace.
❑ from [Module] import * : Import modules's all attributes into the current namespace except start with underbar(_).
❑ import [Module] as [Alias] : Import modules into the current namespace by changing the module name to an alias.
❑ dir(Module name) : Check what functions and data are in the module
❑ How to create a module : Write functions → Store "[Module name].py" to the Python library directory → import [Mudule name] → Use it as this format [Module name].[Function name]
❑ Search order for module path : The directory where the program was executed → The path registered in the PYTHONPATH environment variable → Standard library directory.
❑ Bytecode is generated when importing module.
* Bytecode(~.pyc) : it makes importing faster.
* If there is no bytecode, the module is loaded after it is interpreted to generate bytecode.
❑ __name__ : Check whether the module is directly executed or imported.
* Executed directly : The value of "__name__" is "__main__"
* Imported : The value of "__name__" is module's name.
❑ Package is a collection of modules.
❑ pip is a software to install Python packages registered in PyPI(Python Package Index).
* pip2 is for Python 2.x and pip3 is for Python 3.x.
❑ $ pip3 list: Check installed Python3 modules.
[Misc]
❑ \r : Carriage return.
❑ False : 0, 0.0, (), [], ‘’, None, 5>10
❑ True : All syntax except False.
❑ bool(5>10) : Check true or false.
❑ Number can't appear first in a variable name.
❑ 0x95(Hexadecimal), 1566(Decimal), 0o66(Octal) 0b0110(Binary)
❑ // : Integer division operator.
❑ ** : Power operator.
❑ A tuple is similar to a list, but is read-only
* (1, 2, 3) ("a", "b", "c")
❑ pass : Do nothing.
❑ help([Function name]) : Check the description of the function
❑ Iterater : An object that accesses the iterable objects in order.
>>> s = ‘abc’
>>> it = iter(s)
>>> next(it) → ‘a’ next(it) → ‘b’
>>> it = iter(s)
>>> next(it) → ‘a’ next(it) → ‘b’
❑ type(test1.read()) : Check data type of "test1.read()".
❑ Short evaluation : If the subsequent evaluation does not affect the outcome, it is not evaluated.
* ‘and’ and ‘or’ is applied short evaluation.
* In "[con1] or [con2]", if [con1] is True, the result is Ture. [con2] isn't evaluated.
* print("" or "abc") → abc
* print("" and "abc") → ""
❑ range(Start value, End value, Increment value) : return a sequence.
* The result is returned in iterator format.
* list(range(10, 20, 2)) → [10, 12, 14, 16, 18]
* 0 is assigned when start value is omitted and 1 is assigned when increment value is omitted
❑ map([Function], [Sequence object]) : Executes the function while traversing the sequence object.
def add10(x):
return x+10
lst = [1, 2, 3]
map(add10, lst) → [11, 12, 13]
return x+10
lst = [1, 2, 3]
map(add10, lst) → [11, 12, 13]
❑ filter([Function], [Sequence object]) : Filter a sequence object to return the list of what is true.
* The filtered result is returned in iterator format.
* Filtering is performed by the function. "None" doesn't filters.
def abc(i):
return i > 20
list(filter(abc, Lst1))
def abc(i):
return i > 20
list(filter(abc, Lst1))
❑ To use global variables, it must be declared in advance : global var1
❑ vars([Object]) : Returns object's attribute __dict__. It is same as [Object].__dict__
* vars(process("/bin/echo 123")) : Return information of the run.
* [Instance].__class__.__dict__ : Return members of the class.
❑ Idiomatic expression : Since there is no main() function in Python, People make the main() function idiomatically like below. This is helpful for source code maintenance.
def main():
~
~
if __name__=="__main__":
main()
~
~
if __name__=="__main__":
main()
❑ print("{str1} + {str2} = {str3}".format(str1=1, str2=2, str3=3)) → "1 + 2 + 3"
❑ print("%d + %d = %d"%(1, 2, 3)) → 1 + 2 = 3
❑ print(12345, end="") → 12345 (without newline charactor)
❑ Complex number(복소수)
* e.g. 10+12j → aComplex.real : 10.0 / aComplex.imag : 12.0
❑ a,b=b,a : The values of the a and the b change each other(swap).
❑ Regular expression : Refer "re" module example here.
❑ Random value : Refer "random" module example here.
❑ python argument(argv) : Refer here.
❑ os.system("[Command]") : Execute a shell command.
❑ Read/write with file(b:binary mode, t:text mode).
f = open("/tmp/text.txt", mode="at", encoding="utf-8")
f.write("Test message\n")
f.close()
rst = f.read()
f.write("Test message\n")
f.close()
rst = f.read()
❑ pdb: Python debuger(link).
❑ Create HTTP request message(link).
❑ Check a library path.
import os
import pickle
print(os.path.abspath(pickle.__file__)) # pickle's path.
import pickle
print(os.path.abspath(pickle.__file__)) # pickle's path.
❑ Check a function code.
import inspect
print(inspect.getsource(add)) # add's source.
print(inspect.getsource(add)) # add's source.
❑ Print bytes type data.
import sys
sys.stdout.buffer.write(b"\xdf\x61")
sys.stdout.buffer.write(b"\xdf\x61")
❑ How to use scapy Python module(related pcap, network): Refer here.