Professional Documents
Culture Documents
PYTHON
COURSE OUTLINE
PREPARATION
PREPARATION
PREPARATION
PREPARATION
PREPARATION
RUN JUPYTER
>> jupyter-notebook
Goto : localhost:8888
Jupyter: http://localhost:8888
WHY PYTHON?
WHY PYTHON?
WHY PYTHON?
WHY PYTHON?
Cross Platform
BASIC I/O
BASIC I/O
Hello World
Input
Input()
Output
> print(hello)
> print(10)
> print(text)
> print({}.format(x))
> print(%s.%(x))
print()
Dynamics Variable
>a=1
> a = 1
> a = 1.0
> a = f()
Expression
> pi = pi + 1
> number += 1
> text = text + haha
>n=2+2*2-5
n?
Variable types
boolean
: True/False
float
int
: 100
string
0.1
hello
>> type()
10 Min.
Quiz Time
Input:
FRIST NAME:
LAST NAME:
AGE:
GENDER:
TEL:
WEIGHT (KG.):
HEIGHT (CM.) :
Output:
*1 kg = 2.205 lb
MY NAME IS ________________.
I AM _________ YEARS OLD.
I AM A _________.
MY PHONE NO. IS ______________.
MY WEIGHT IS ________________KG. (~_________ LB.)
MY HEIGHT IS ________________CM. (~__________M.)
Q1
CONDITIONAL CODE
CONDITIONAL CODE
Syntax
Comparators
if
<condition> :
statment(s)
elif <condition> :
statment(s)
else :
statment(s)
Syntax
short if
x = <true> if <condition> else <false>
Operators
A & B , A and B
A | B
, A or B
CONDITIONAL CODE
Example
x = 5 if 5 > 10 else 10
print(False)
elif (10 > 5) & (not(False)):
print(True)
else:
print(NULL)
CONDITIONAL CODE
5 Min.
Quiz Time
Input:
FRIST NAME:
LAST NAME:
AGE:
GENDER:
TEL:
WEIGHT (KG.):
HEIGHT (CM.) :
Output:
*1 kg ~ 2.205 lb
MY NAME IS ________________.
I AM _________ YEARS OLD.
I AM A _________.
MY PHONE NO. IS ______________.
MY WEIGHT IS ________________KG. (~_________ LB.)
MY HEIGHT IS ________________CM. (~__________M.)
MY BMI IS : __________________.
Q2
range
#generate number
range(5) ==> [0,1,2,3,4]
range(0,10,2) ==> [0,2,4,6,8]
range(0,10,5) ==> [0,5]
enumerate
#generate index i start from 0
for i, n in enumerate(<iterator object>):
statement(s)
Example
for i, n in enumerate(range(0,10,5)):
pow = n ** i
print(pow)
1
5
Syntax
Examples
for
for
for n in range(10):
print(n ** n)
while..
while(<conditions>):
statement(s)
while..
while(True):
break
continue
#next loop
for n in <iterator object>:
continue
break
#exit loop
for n in <iterator object>:
break
pass
#pass
while True
pass
Syntax
for
for n in <iterator object>:
statement(s)
while..
while(<conditions>):
statement(s)
range
#generate index number
range(5) ==> [0,1,2,3,4]
range(0,10,2) ==> [0,2,4,6,8]
enumerate
#generate index i start from 0
for i, n in enumerate(<iterator object>):
statement(s)
continue
break
#next loop
#exit loop
FUNCTION
FUNCTIONS
Syntax
return
return 0
return 1
g = make_generator()
print(g)
0
FUNCTIONS
Argument
def foo(x = 1, y = 2) :
statement(s)
fn(3,2) #args
fn(x = 2, y = 1) #kwargs
FUNCTIONS
Return
Example
def add(x, y) :
statement(s)
a=x+y
return value
return a
Return
Example
def minmax(x, y) :
if x == y:
return None, None
statement(s)
return value1, value2,
Return values
x , y = minmax(x,y)
mi = x if x < y else y
ma = x if x > y else y
return mi, ma
FUNCTIONS
Example
def BMI(weight=None, height =None):
bmi = weight / (height ** 2)
return bmi
bmi = BMI(10,1.67)
FUNCTIONS
#Variable scope
#Variable scope
r = 1
for a in range(10):
r = 3
for i in range(5):
r=8
a = 5
def var():
print(a)
print(r) ????
var() ????
#Variable scope
a = 5
def var():
a += 5
print(a)
var() ????
FUNCTIONS
#Variable scope
a = 5
def var():
global a
a += 5
print(a)
var() ????
FUNCTIONS
10 Min.
Quiz Time
Q3
FUNCTIONS
#main program
import bmi
bmi.getInfo()
bmi.BMI(weight,height)
bmi.showInfo()
#main program
from bmi import bmi
bmi.getInfo()
bmi.BMI(weight,height)
bmi.showInfo()
#External function
#bmi.py
def getInfo():
def BMI(weight,height):
..
def showInfo(.,..,.):
def BMI(weight,height):
..
def showInfo(.,..,.):
- LIST
- TUPLE
- SET
- DICT
- FILE
List
[1,2,3,4,5,6,7,8,9,10]
stack.pop()
print(stack)
stack.pop()
stack.pop()
print(stack)
queue.append("Graham")
queue.popleft()
queue.popleft()
print(queue)
Add element
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
Generate list
squares = [x**2 for x in range(10)]
squares = list(map(lambda x: x**2, range(10)))
map
map( lambda <> , <>, <input>) #~ short for
Nested List
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
Transpose List
list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
sorted
a = [10,2,3,4,5,6,7,8,9,1]
print(sorted(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Concat List
a = [1,2,3,4]
b = [5,6,7,8,9]
c=a+b
print(c)
[1,2,3,4,5,6,7,8,9]
del
FUNCTIONS
10 Min.
Quiz Time
STATISTICS Time
http://www.mathsisfun.com/data/standard-deviation.html
Q4
Concat Tuple
a = 1,2,3,4,5,6,[1],hello"
a += tuple([100])
print(a)
(1, 2, 3, 4, 5, 6, [1], 'hello', 100)
List to Tuple
t = tuple([1,2,3,4,5,6])
print(t)
(1, 2, 3, 4, 5, 6)
Sets
{'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
Sets
a = {'apple', 'orange', 'apple', 'pear', 'orange', banana'}
print(a)
{'apple', 'orange', 'banana', 'pear'}
a = set(ABCDEFG)
print(a)
{'E', 'B', 'A', 'F', 'G', 'C', 'D'}
a = set([4,5,1,2,3])
print(a)
{1, 2, 3, 4, 5} #element will be sorted automatically
a = set([4,5,1,2,3])
b = set([4,5,1])
print(a.intersection(b))
{1, 4, 5}
5 Min.
Quiz Time
Like Number
Similarity?
Q5
5 Min.
Q5
Like Number
Quiz Time
5 Min.
Quiz Time
Like Number
Q5
5 Min.
Quiz Time
Q5
5 Min.
Quiz Time
Like Number
Q5
Dict
{'apple' : 0, 'orange' : 1, 'pear' : Hello'}
File
f = open(<filename>,r) #open file for read
f = open(<filename>,w) #open file for write new
f = open(<filename>,a) #open file for write append
f.readline() #read next line
f.readlines() #read all lines
f.close() #read all lines
file.txt
My name is python.
I am a programmer.
I have no life.
with open(file.txt , r) as f:
first = f.readline()
for line in f:
print(line)
My name is Python.
I am a programmer.
I have no life.
file.txt
My name is python.
I am a programmer.
I have no life.
with open(file.txt , r) as f:
lines = f.readlines()
print(lines)
['My name is Python.\n', 'I am a programmer.\n', 'I have no life.']
with open(write.txt , w) as f:
f.write(Hello\n)
write.txt
Hello
with open(write.txt , a) as f:
f.write(World\n)
write.txt
Hello
World
file.txt
My name is python.
I am a programmer.
I have no life.
f = open(file.txt , r)
lines = f.readlines()
print(lines)
f.close()
['My name is Python.\n', 'I am a programmer.\n', 'I have no life.']
String
str = hello world #create string
len(str) #get string length
str[i:j] # get string from index i to index j - 1
str[i] #get character at index i
str.replace(str1,str2) #replace str1 with str2 in string str
str.splite(sep) #split string by string sep
https://docs.python.org/2/library/string.html
10 Min.
Quiz Time
file.txt
My name is python
I am a programmer
I have no life
Q6
Word Count
I : 2
my : 1
name : 1
is : 1
..
try:
...
except SomeException:
e = sys.exc_info()[1]
print(e)
https://docs.python.org/3/library/exceptions.html
import sys
try:
str = "hello"
print(str[100])
except:
tb = sys.exc_info()[1]
print(tb)
string index out of range
https://docs.python.org/3/library/exceptions.html
Input validation
while(True):
try:
n = int(input("age : "))
break
except:
print("Age is invalid, please try agian.")
https://docs.python.org/3/library/exceptions.html
5 Min.
Quiz Time
Input validation
FRIST NAME:
LAST NAME:
AGE:
GENDER:
TEL:
WEIGHT (KG.):
HEIGHT (CM.) :
Q7
class ClassName:
'Optional class documentation string'
class_suite
https://www.tutorialspoint.com/python/python_classes_objects.htm
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print("Total Employee %d") % Employee.empCount
https://www.tutorialspoint.com/python/python_classes_objects.htm
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
https://www.tutorialspoint.com/python/python_classes_objects.htm
Class Inheritance
https://www.tutorialspoint.com/python/python_classes_objects.htm
class Child(Parent):
def __init__(self):
print(Calling parent constructor)
def __init__(self):
print(Calling child constructor)
def childMethod(self):
print(Calling child method)
def parentMethod(self):
print(Calling parent method)
Accessing
c = Child()
# instance of child
c.childMethod()
c.parentMethod()
c.setAttr(200)
c.getAttr()
https://www.tutorialspoint.com/python/python_classes_objects.htm
Overriding Methods
class Parent:
def myMethod(self):
print 'Calling parent method'
class Child(Parent):
def myMethod(self):
print 'Calling child method'
c = Child()
# instance of child
c.myMethod()
https://www.tutorialspoint.com/python/python_classes_objects.htm
Data Hiding
class JustCounter:
__secretCount = 0 #add double underscore prefix
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
https://www.tutorialspoint.com/python/python_classes_objects.htm
10 Min.
Quiz Time
My Car
Q8
MULTITHREADED PROGRAMMING
MULTITHREADED PROGRAMMING
MULTITHREADED PROGRAMMING
MULTITHREADED PROGRAMMING
Background Executor
thread.start_new_thread ( function, args[, kwargs] )
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
MULTITHREADED PROGRAMMING
Parallele Processing
p = Pool(<Number of Executor>)
p.map(<function>,data)
p = Pool(5)
ans = p.map(f, [1, 2, 3])
[1, 4, 9]
- Use it if you have more than one/two cores on your computer and
more data point, overhead will occur when start new thread
https://github.com/tomerfiliba/rpyc
Using library
import <packet name>
from <packet folder name> import <packet name>
import time
t = time.time()
import time
t = time.time()
def printMe(text)
printMe(text)
server slide
import rpyc
from rpyc.utils.server import ThreadedServer
class MyService(rpyc.Service):
def exposed_add(self, a, b):
return a + b
def exposed_sub(self, a, b):
return a - b
def exposed_mul(self, a, b):
return a * b
def exposed_div(self, a, b):
return a / b
def foo(self):
print foo"
if __name__ == "__main__":
server =
ThreadedServer(MyService, port = 12345)
server.start()
client slide
import rpyc
import rpyc
conn = rpyc.connect("localhost", 12345)
x = conn.root.add(4,7)
print(x)