Thursday, August 24, 2017

[programming-0] Quick Python

Short tutorial on Python programming language. The contents are taken from these sources MIT OCW[2] and the book Introduction to Computation and Programming using Python[1] by John V. Guttag. To understand this document you are expected to know a programming language well.

Comment
#single line comment
"""
multi line comment """

Basic Operations
+, -, / %, *
2 ** 3 // 2 to the power 3

Variable assignment
a = 3

Global variable

global variable_name //creates entry for this identifier in outermost stack frame

Conditionals
a or b
a and b
not a
a == b
a != b

Program flow
if condition:
code block
elif condition:
code block
else:
code block

Loop
while condition:
code block

for var in range(0, 10):
code block

Break execution of loop
break

Continue to next iteration
continue

Function 
Declaration
def functionName(arg1, arg2):
code block

Call
functionName(param1, param2)

Tuple
tuples are immutable
t1 = (1, 2, 3)
t2 = (4, 5, 6)

access element
t1[2]
t1[2:3]

joining tuples
t3 = t1 + t2 //t1 and t2 are immutable so there is no side effect, meaning t1 and t2 will be unmodified

assign multiple variables using tuple
x, y, z = (0, 1, 2) //x <- 0, y <- 1, z <- 2

List
Mutable, meaning an element can be added or removed

Initialize
lst = [1, "saif", 2.3] //can hold different type of elements
lst = [x for x in range(0, 10)]

Element Access
lst[i]

Insert
l.append(element)

Traverse
for i in range(len(L)):
print(L[i])

Useful methods
append(e) //adds e at the end of the list
count(e) //occurances of e
insert(index, element)
extend(list2) //inserts all elements of list2 to this list
remove(e)
index(e)
pop(i)
sort()
reverse()

cloning list
list(l)
copy.deepcopy()


String 
strings are immutable

Initialize
str = "abc"

Methods
str.count(s2)
str.find(s2)
str.rfind(s2) //find the first occurance from backward
str.index(s2)
str.rindex(s2)
str.lower()
str.replace(old, new)
str.rstrip() //remove white space from right
str.split(delimeter)

Dictionary
Initialize
dict = {k1:v1, k2:v2, k3:v3}

Insert
dict[key] = value

Access
value = dict[key]


Delete
del dict[key]

Iterate
for key in dict:

Useful methods
length : len(dict)
keys: dict.keys()
values: dict.values()
element exists: key in dict
default value to return: d.get(key, default_value)  //returns default value if key is not present

Common methods for String, List, Tuple
access i th element: seq[i]
length: len(seq)
merge: seq1 + seq2
create multiple: n * seq //"abc"*3 -> "abcabcabc"
subsequence: seq[start:end]
element exists: e in seq
element does not exist: e not in seq
traverse: for e in seq:

Useful methods for objects
append(e) //adds e at the end of the list
count(e) //occurances of e
insert(index, element)
extend(list2) //inserts all elements of list2 to this list
remove(e)
index(e)
pop(i)
sort()
type()
isInstance(object, ClassName)

File

Writing
file = open("filename", "w") // for append "a", for reading "r"
file.write(line)
file.close()

Reading
file = open("filename", "r")
for line in file:
print(line)
file.close()

Writing code in modules
file name: file1.py
var1 = 2
var2 = 3
def method1:
print "hello"

file name: b.py
import file1

print file1.var1
file1.method1()

Exception Handling

Handle exception
try:
    result = a / b
except ErrorName0:
    codeBlock
except (ErrorName1, ErrorName2):
    codeBlock
except: # default case
    codeBlock

Raise Exception
raise ExceptionName(argument)
raise ValueError('Bad Value You Provided!')

Assertion
assert booleanExpression
assert booleanExpression, arguments

assert temperature > 80, "too hot" #if temperature gets more than 80, the message will be printed with error message

Class
class ClassName(ExtendClass):
    classVariable = 0
    def __init__(self):
        self.instanceVariable = 8
    def __lt__(self, other):
        #compare with another object
    def __str__(self):

    def otherMethods(self, arg0, arg1):

Instantitate
a = ClassName()

Yield
list = [1, 2, 3 ,4]

def yield_one_by_one():
     for elem in list:
         yield s
for elem in yield_one_by_one():
         print(elem)


[1] https://www.amazon.com/exec/obidos/ASIN/0262529629/ref=nosim/mitopencourse-20
[2] https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/index.htm

No comments:

Post a Comment