SlideShare a Scribd company logo
1 of 92
Download to read offline
$ python --version
helloworld.py
print 'Hello world'
print
$ python helloworld.py
Hello world
a = 1
a = 1
a = 'Hello World'
a = [1, 2, 3]
a = [1.2, 'Hello', 'W', 2]
+
-
*
/
%
True False
not
and
or
< <=
> >= ==
!=
x = 2
1 < x < 3 # True
10 < x < 20 # False
3 > x <= 2 # True
2 == x < 4 # True
in
not in
'good' in 'this is a greate example' # F
alse
'good' not in 'this is a greate example' # True
{ }
if condition1 :
indentedStatementBlockForTrueCondition1
elif condition2 :
indentedStatementBlockForFirstTrueCondition2
elif condition3 :
indentedStatementBlockForFirstTrueCondition3
elif condition4 :
indentedStatementBlockForFirstTrueCondition4
else:
indentedStatementBlockForEachConditionFalse
switch case
for iterating_var in sequence:
statements(s)
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
while expression:
statement(s)
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
def functionname(param, param2,..):
statements(s)
None
def sum(a, b):
return (a+b)
sum(1, 2)
(trả về giá trị là 3)
def plus(c, d = 10):
return (c+d)
plus(2)
(kết quả trả về là 12)
sum(a,b) b a
sum(b = 1, a = 10)
"
'
str1 = "Hello"
str2 = 'world'
str1[0] str1[1]
paragraph = """This is line 1
This is line 2
This is line 3"""
str = str1 + " " + str2
[start:end] start
0 end
str = 'Hello world'
print str[0:4]
(Hiển thị "Hell")
print str[:4]
(Hiển thị "Hell")
print str[-3:]
(Hiển thị "rld")
print str[6:-3]
(Hiển thị "wo")
len(...)
count = len("Hello world")
(count có giá trị 11)
replace(search, replace[, max])
str = 'Hello world'
newstr = str.replace('Hello', 'Bye')
print newstr
(Sẽ hiển thị chuỗi "Bye world" trên màn hình)
find(str, beg=0
end=len(string)) 0
-1
str = 'Hello world'
print str.find('world')
(hiển thị 6)
print str.find('Bye');
(hiển thị -1)
find()
rfind()
split(str="", num=string.count(str))
str = 'Hello world'
print str.split(' ')
(Trả về một mảng có 2 phần tử là 2 chuỗi "Hello" và
"world")
splitlines()
strip([chars])
lstrip([chars])
rstrip([chars])
isnumeric()
lower()
upper()
[..]
numbers = [1, 2, 3, 4, 5]
names = ['Marry', 'Peter']
0
print numbers[0]
(Hiển thị 1)
print numbers[-3]
(Hiển thị 3)
print names[1]
(Hiển thị 'Peter')
len(array)
if index < len(array):
array[index]
else:
# handle this
try:
array[index]
except IndexError:
# handle this
in not in
mylist = ['a', 'b', 'c']
print 'a' in mylist
(Hiển thị True)
print 'b' not in mylist
(Hiển thị False)
[start:end] start
0 end
numbers = ['a', 'b', 'c', 'd']
print numbers[:2]
(Hiển thị ['a', 'b'])
print numbers[-2:]
(Hiển thị ['c', 'd'])
del
numbers = [1, 2, 3, 4, 5]
del numbers[0]
print numbers
(Hiển thị [2, 3, 4, 5])
[start:end]
numbers = [1, 2, 3, 4, 5, 6, 7]
del numbers[2:4]
print numbers
(Hiển thị [1, 2, 5, 6, 7])
+
a = [1, 2]
b = [1, 3]
print a + b
(Hiển thị [1, 2, 1, 3])
list.append(newvalue)
newvalue list
numbers = [1, 2, 3]
numbers.append(4)
print numbers
(Hiển thị [1, 2, 3, 4]
list.pop()
numbers = [1, 2, 3]
mynumber = numbers.pop()
print mynumber
(Hiển thị 3)
print numbers
(Hiển thị [1, 2])
list.index(obj)
aList = [123, 'xyz', 'zara', 'abc'];
print "Index for xyz : ", aList.index('xyz')
print "Index for zara : ", aList.index('zara')
Index for xyz : 1
Index for zara : 2
list.reverse()
list
numbers = [1, 2, 3, 4]
numbers.reverse()
print numbers
(Hiển thị [4, 3, 2, 1])
list.sort([func])
func
list
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.sort()
print "List : ", aList
(Hiển thị List : [123, 'abc', 'xyz', 'xyz', 'zara'
])
func()
0 -1 1
(...)
append() pop()
mytuple = ('x', 'y', 'z')
print mytuple
(Hiển thị ('x', 'y', 'z'))
{...}
point = {'x': 1, 'y': 2}
point = {'x': 3, 'y': 6, 'z' : 9}
print point[x]
(Hiển thị 3)
dict[key] = value
user = {'name': 'Jone', 'age': 30}
user['country'] = 'Vietnam'
print user
(Hiển thị {'country': 'Vietnam', 'age': 30, 'name':
'Jone'})
dict.clear()
dict.copy()
dict.fromkeys(seq[, value])
value
dict.has_key(key)
dict.keys()
dict.values()
.py
.py
.dll
.pyd .so .sl
import modulename
import math
math.__file__
(Ví dụ trả về '/usr/lib/python2.5/lib-dynload/math.
so')
import random
random.__file__
(Ví dụ trả về '/usr/lib/python2.5/random.pyc')
dir(modulename)
dir(math)
['__doc__', '__file__', '__name__', '__package__',
'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degree
s', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'fa
ctorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma'
, 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'lo
g', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians
', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
dir()
mymath.py
def cong(a, b):
return a + b
def tru(a, b):
return a - b
def nhan(a, b):
return a * b
myexample.py
mymath.py
import mymath
num1 = 1
num2 = 2
print 'Tong hai so la: ', mymath.cong(num1, num2)
$ python myexample.py
Tong hai so la: 3
.py
__init__.py
|-- mypack
| |-- __init__.py
| |-- mymodule1.py
| |-- mymodule2.py
|
mymodule1
import mypack.mymodule1
import mypack.mymodule1 as mymodule1
import mypack.mymodule1 as mod
__init__.py
__init__.py
__init__.py
import mypack.mysubpack.mysubsubpack.module
class myclass([parentclass]):
assignments
def __init__(self):
statements
def method():
statements
def method2():
statements
class animal():
name = ''
name = ''
age = 0
def __init__(self, name = '', age = 0):
self.name = name
self.age = age
def show(self):
print 'My name is ', self.name
def run(self):
print 'Animal is running...'
def go(self):
print 'Animal is going...'
class dog(animal):
def run(self):
print 'Dog is running...'
myanimal = animal()
myanimal.show()
myanimal.run()
myanimal.go()
mydog = dog('Lucy')
mydog.show()
mydog.run()
mydog.go()
My Name is
Animal is running...
Animal is going...
My Name is Lucy
Dog is running...
Animal is going...
animal dog dog
animal
animal
name age
__init__(self)
show() run() go()
self
run() dog override
run() animal
fh = open(filepath, mode)
filepath mode
r
w
a
r+
w+
a+
b rb wb ab rb+ wb+ ab+
f1 = open('test.txt', 'r')
f2 = open('access_log', 'a+'
open()
closed
mode
name
softspace
print
read([count])
f1 = open('test.txt', 'r')
data = f1.read();
read()
f2 = open('log.txt', 'r')
buffdata = f2.read(1024)
write()
f2 = open('access_log', 'a+')
f2.write('Attack detected')
close()
f1.close()
f2.close()
os.rename(old, new)
import os
os.rename('test.txt', 'test_new.txt')
os.remove(file)
import os
os.remove('test.txt')
os.mkdir(dir)
import os
os.mkdir('test')
os.rmdir(dir)
import os
os.rmdir('test')
os.listdir(dir)
dir
import os
allfiles = os.listdir('/root/downloads')
print allfiles
os
os
os.chdir(path)
os.getcwd()
os.chmod(path, mode)
os.chown(path, uid, gid)
os.makedirs(path[, mode])
os.removedirs(path)
os.path
os.path
os.path.exists(path)
os.path.getsize(path)
os.path.isfile(path)
os.path.isdir(path)
os.path.dirname(path)
os.path.getatime(path)
os.path.getmtime(path)
os.path.getctime(path)
from PIL import Image
from PIL import Image
im = Image.open("photo.jpg")
im
Image
save(path, type)
...
im.save('photo_new.jpg', 'JPEG')
thumbnail
from PIL import Image
im = Image.open('photo.jpg')
im.thumbnail((100, 100))
im.save('photo_thumbnail.jpg', 'JPEG')
thumbnail
urllib2
json
import urllib2
import json
response = urllib2.urlopen('https://api.github.com/
users/voduytuan/repos')
data = json.load(response)
print data
import json
mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
data = json.loads(mystring)
print data
(Hiển thị: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd
': 4})
import json
mydata = {
'name': 'John',
'age': 10
}
jsonstring = json.dumps(mydata)
print jsonstring
(hiển thị: {"age": 10, "name": "John"})
pip
$ sudo pip install beautifulsoup4
lxml
xml
lxml
pip
sudo pip install lxml
from bs4 import BeautifulSoup as Soup
note = '''
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waff
les with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered
with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>
'''
soup = Soup(note, 'xml')
foods = soup.findAll('food')
for x in foods:
print x.find('name').string, ': ', x.price.stri
ng
Belgian Waffles : $5.95
Strawberry Belgian Waffles : $7.95
Soup
findAll()
find()
x.price.string
xml
html
...
soup = Soup(websitehtml, 'html')
MySQLdb
pip
$ sudo pip install MySQL-python
import MySQLdb
libmysqlclient.18.dylib
libmysqlclient.18.dylib /usr/lib/
$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18
.dylib /usr/lib/libmysqlclient.18.dylib
import MySQLdb
dbcon = MySQLdb.connect(host = 'localhost', user =
'myusername', passwd = 'mypassword', db = 'mydbname
')
try
import MySQLdb
db = None
try:
db = MySQLdb.connect(host = 'localhost', user =
'root', passwd = 'root', db = 'mysql')
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
if db:
cur = db.cursor()
cur.execute("SELECT VERSION()")
ver = cur.fetchone()
print "Database version : %s " % ver
charset utf8
latin
utf8
...
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'test', charset = 'utf8'
)
cursor
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'mysql');
cursor = db.cursor()
sql = 'SELECT * FROM user'
cursor.execute(sql)
myusers = cursor.fetchall()
myusers ((1, 'John'), (2, 'Doe'))
cursor
tuple
Dictionary
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'mysql')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
...
cursor
exectute(sql) fetchone() fetchall()
fetchone()
None
fetchall()
fetchmany(size)
import MySQLdb
db = MySQLdb.connect(...)
db.close()
cursor
import MySQLdb
db = MySQLdb.connect(...)
cursor = db.cursor()
cursor.close()
db.close()
...
cur.execute("UPDATE Writers SET Name = %s WHERE Id
= %s", ("John", "4"))
...
%s
execute()
%s
pip
$ sudo pip install redis
import redis
r = redis.StrictRedis(host='localhost', port=6379,
db=0)
import redis
r = redis.StrictRedis(...)
r.set('foo', 'bar')
print r.get('foo')
(Hiển thị 'bar')
redis-py
import redis
r = redis.StrictRedis(...)
r.set('foo', 'bar')
pipe = r.pipeline()
pipe.set('a', 1)
pipe.set('b', 2)
pipe.set('c', 3)
pipe.get('foo')
pipe.execute()
execute()
[True, True, True, 'bar']
pylibmc
pip
$ sudo pip install pylibmc
import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True, beh
aviors={"tcp_nodelay": True, "ketama": True})
import pylibmc
mc = pylibmc.Client(...)
mc.set('foo', 'bar')
print mc.get('foo')
(Hiển thị 'bar')
pika
pip
$ sudo pip install pika
import pika
connection = pika.BlockingConnection(pika.Connectio
nParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='hel
lo', body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
hello
Hello World!
routing_key hello
hello
import pika
connection = pika.BlockingConnection(pika.Connectio
nParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTR
L+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback, queue='hello', no_a
ck=True)
channel.start_consuming()
connection
channel
basic_consume
hello callback()
pika
requests
pip
$ sudo pip install requests
import requests
r = requests.get('https://api.github.com/events')
r = requests.post("http://httpbin.org/post")
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")
GET
params get()
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params =
payload)
print(r.url)
(Hiển thị: http://httpbin.org/get?key2=value2&key1=
value1)
data
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data =
payload)
files
import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
Response
status_code
headers
cookies
text
requests
smtplib
sender
sender
pip
$ sudo pip install sender
sender
from sender import Mail, Message
mail = Mail(
"smtp.gmail.com",
port = 465,
username = "example@gmail.com",
password = "yourpassword",
use_tls = False,
use_ssl = True,
debug_level = False
)
msg = Message("msg subject")
msg.fromaddr = ("Vo Duy Tuan", "example@gmail.com")
msg.to = "destuser@gmail.com"
msg.body = "this is a msg plain text body"
msg.html = "<b>this is a msg text body</b>"
msg.reply_to = "example@gmail.com"
msg.charset = "utf-8"
msg.extra_headers = {}
msg.mail_options = []
msg.rcpt_options = []
# Send message
mail.send(msg)
from sender import Mail, Message, Attachment
mail = Main(...)
msg = Message(..)
...
# Open attached file and create Attachment object
with open("photo01.jpg") as f:
file01 = Attachment("photo01.jpg", "image/jpeg"
, f.read())
msg.attach(file01)
# Send message
mail.send(msg)
sender
server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
Got connection
from Got connection from ('192.168.1.104', 60018)
Thank you for
connecting
client.py
import socket
s = socket.socket()
host = '127.0.0.1'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
socket.gethostname()

More Related Content

What's hot

Phân tích và thiết kế hệ thống quản lý bán hàng
Phân tích và thiết kế hệ thống quản lý bán hàngPhân tích và thiết kế hệ thống quản lý bán hàng
Phân tích và thiết kế hệ thống quản lý bán hàngleemindinh
 
C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...
C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...
C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...Long Kingnam
 
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư việnThe Nguyen Manh
 
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng HồBáo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng HồzDollz Lovez
 
Đồ Án Thiết Kế Mạng ĐHCNTPHCM
Đồ Án Thiết Kế Mạng ĐHCNTPHCMĐồ Án Thiết Kế Mạng ĐHCNTPHCM
Đồ Án Thiết Kế Mạng ĐHCNTPHCMTeemo Hành Gia
 
Đề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuật
Đề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuậtĐề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuật
Đề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuậtHưởng Nguyễn
 
Chương 4. Chuẩn hóa cơ sở dữ liệu
Chương 4. Chuẩn hóa cơ sở dữ liệu Chương 4. Chuẩn hóa cơ sở dữ liệu
Chương 4. Chuẩn hóa cơ sở dữ liệu Hoa Le
 
Giải bài tập Phương pháp tính
Giải bài tập Phương pháp tínhGiải bài tập Phương pháp tính
Giải bài tập Phương pháp tínhdinhtrongtran39
 
Hướng dẫn lập trình quản lý c#
Hướng dẫn lập trình quản lý c#Hướng dẫn lập trình quản lý c#
Hướng dẫn lập trình quản lý c#An Nguyen
 
Phân tích thiết kế hệ thống của hàng bán điện thoại di động
Phân tích thiết kế hệ thống của hàng bán điện thoại di độngPhân tích thiết kế hệ thống của hàng bán điện thoại di động
Phân tích thiết kế hệ thống của hàng bán điện thoại di độngNguyễn Danh Thanh
 
Tài liệu tổng kểt môn mạng máy tính
Tài liệu tổng kểt môn mạng máy tínhTài liệu tổng kểt môn mạng máy tính
Tài liệu tổng kểt môn mạng máy tínhJojo Kim
 
Bai07 bo nho
Bai07   bo nhoBai07   bo nho
Bai07 bo nhoVũ Sang
 
Phương pháp tham lam giải bài toán lập lịch công việc
Phương pháp tham lam giải bài toán lập lịch công việcPhương pháp tham lam giải bài toán lập lịch công việc
Phương pháp tham lam giải bài toán lập lịch công việcNguyễn Danh Thanh
 
Giáo trình SQL server tiếng việt
Giáo trình SQL server tiếng việtGiáo trình SQL server tiếng việt
Giáo trình SQL server tiếng việtThuyet Nguyen
 
bao cao linux
bao cao linuxbao cao linux
bao cao linuxbinhnv186
 
Do an xay_dung_website_thuong_mai_dien_tu
Do an xay_dung_website_thuong_mai_dien_tuDo an xay_dung_website_thuong_mai_dien_tu
Do an xay_dung_website_thuong_mai_dien_tuThiênĐàng CôngDân
 
Thiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sựThiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sựleemindinh
 
Thiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sựThiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sựleemindinh
 

What's hot (20)

Phân tích và thiết kế hệ thống quản lý bán hàng
Phân tích và thiết kế hệ thống quản lý bán hàngPhân tích và thiết kế hệ thống quản lý bán hàng
Phân tích và thiết kế hệ thống quản lý bán hàng
 
C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...
C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...
C# Báo cáo môn lập trình hướng đối tượng - Xây dựng chương trinh quản lí sinh...
 
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
 
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng HồBáo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
 
Đồ Án Thiết Kế Mạng ĐHCNTPHCM
Đồ Án Thiết Kế Mạng ĐHCNTPHCMĐồ Án Thiết Kế Mạng ĐHCNTPHCM
Đồ Án Thiết Kế Mạng ĐHCNTPHCM
 
Đề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuật
Đề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuậtĐề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuật
Đề thi mẫu trắc nghiệm cấu trúc dữ liệu cà giải thuật
 
Chương 4. Chuẩn hóa cơ sở dữ liệu
Chương 4. Chuẩn hóa cơ sở dữ liệu Chương 4. Chuẩn hóa cơ sở dữ liệu
Chương 4. Chuẩn hóa cơ sở dữ liệu
 
Giải bài tập Phương pháp tính
Giải bài tập Phương pháp tínhGiải bài tập Phương pháp tính
Giải bài tập Phương pháp tính
 
Hướng dẫn lập trình quản lý c#
Hướng dẫn lập trình quản lý c#Hướng dẫn lập trình quản lý c#
Hướng dẫn lập trình quản lý c#
 
Chuong02
Chuong02Chuong02
Chuong02
 
Phân tích thiết kế hệ thống của hàng bán điện thoại di động
Phân tích thiết kế hệ thống của hàng bán điện thoại di độngPhân tích thiết kế hệ thống của hàng bán điện thoại di động
Phân tích thiết kế hệ thống của hàng bán điện thoại di động
 
Tài liệu tổng kểt môn mạng máy tính
Tài liệu tổng kểt môn mạng máy tínhTài liệu tổng kểt môn mạng máy tính
Tài liệu tổng kểt môn mạng máy tính
 
Bai07 bo nho
Bai07   bo nhoBai07   bo nho
Bai07 bo nho
 
Phương pháp tham lam giải bài toán lập lịch công việc
Phương pháp tham lam giải bài toán lập lịch công việcPhương pháp tham lam giải bài toán lập lịch công việc
Phương pháp tham lam giải bài toán lập lịch công việc
 
Giáo trình SQL server tiếng việt
Giáo trình SQL server tiếng việtGiáo trình SQL server tiếng việt
Giáo trình SQL server tiếng việt
 
Đề tài: Xây dựng phần mềm quản lý quán cà phê, HOT, 9đ
Đề tài: Xây dựng phần mềm quản lý quán cà phê, HOT, 9đĐề tài: Xây dựng phần mềm quản lý quán cà phê, HOT, 9đ
Đề tài: Xây dựng phần mềm quản lý quán cà phê, HOT, 9đ
 
bao cao linux
bao cao linuxbao cao linux
bao cao linux
 
Do an xay_dung_website_thuong_mai_dien_tu
Do an xay_dung_website_thuong_mai_dien_tuDo an xay_dung_website_thuong_mai_dien_tu
Do an xay_dung_website_thuong_mai_dien_tu
 
Thiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sựThiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sự
 
Thiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sựThiết kế csdl quản lý nhân sự
Thiết kế csdl quản lý nhân sự
 

Similar to Lập trình Python cơ bản

Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Python basic
Python basic Python basic
Python basic sewoo lee
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfJkPoppy
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Selective codes
Selective codesSelective codes
Selective codesSiva Gopal
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in ElixirJesse Anderson
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and GoEleanor McHugh
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)Pedro Rodrigues
 

Similar to Lập trình Python cơ bản (20)

Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Clojure入門
Clojure入門Clojure入門
Clojure入門
 
Python basic
Python basic Python basic
Python basic
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
Selective codes
Selective codesSelective codes
Selective codes
 
Basics
BasicsBasics
Basics
 
Python
PythonPython
Python
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in Elixir
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 

Recently uploaded

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Recently uploaded (20)

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

Lập trình Python cơ bản

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 9. a = 1 a = 1 a = 'Hello World' a = [1, 2, 3] a = [1.2, 'Hello', 'W', 2] +
  • 11. x = 2 1 < x < 3 # True 10 < x < 20 # False 3 > x <= 2 # True 2 == x < 4 # True in not in 'good' in 'this is a greate example' # F alse 'good' not in 'this is a greate example' # True { }
  • 12. if condition1 : indentedStatementBlockForTrueCondition1 elif condition2 : indentedStatementBlockForFirstTrueCondition2 elif condition3 : indentedStatementBlockForFirstTrueCondition3 elif condition4 : indentedStatementBlockForFirstTrueCondition4 else: indentedStatementBlockForEachConditionFalse switch case for iterating_var in sequence: statements(s)
  • 13. for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second Example print 'Current fruit :', fruit print "Good bye!" Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye!
  • 14. while expression: statement(s) count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
  • 15. The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye! def functionname(param, param2,..): statements(s) None
  • 16. def sum(a, b): return (a+b) sum(1, 2) (trả về giá trị là 3) def plus(c, d = 10): return (c+d) plus(2) (kết quả trả về là 12)
  • 17. sum(a,b) b a sum(b = 1, a = 10) " ' str1 = "Hello" str2 = 'world' str1[0] str1[1]
  • 18. paragraph = """This is line 1 This is line 2 This is line 3""" str = str1 + " " + str2 [start:end] start 0 end
  • 19. str = 'Hello world' print str[0:4] (Hiển thị "Hell") print str[:4] (Hiển thị "Hell") print str[-3:] (Hiển thị "rld") print str[6:-3] (Hiển thị "wo") len(...) count = len("Hello world") (count có giá trị 11)
  • 20. replace(search, replace[, max]) str = 'Hello world' newstr = str.replace('Hello', 'Bye') print newstr (Sẽ hiển thị chuỗi "Bye world" trên màn hình) find(str, beg=0 end=len(string)) 0 -1 str = 'Hello world' print str.find('world') (hiển thị 6) print str.find('Bye'); (hiển thị -1) find()
  • 21. rfind() split(str="", num=string.count(str)) str = 'Hello world' print str.split(' ') (Trả về một mảng có 2 phần tử là 2 chuỗi "Hello" và "world") splitlines()
  • 23. numbers = [1, 2, 3, 4, 5] names = ['Marry', 'Peter'] 0 print numbers[0] (Hiển thị 1) print numbers[-3] (Hiển thị 3) print names[1] (Hiển thị 'Peter') len(array)
  • 24. if index < len(array): array[index] else: # handle this
  • 25. try: array[index] except IndexError: # handle this in not in mylist = ['a', 'b', 'c'] print 'a' in mylist (Hiển thị True) print 'b' not in mylist (Hiển thị False) [start:end] start
  • 26. 0 end numbers = ['a', 'b', 'c', 'd'] print numbers[:2] (Hiển thị ['a', 'b']) print numbers[-2:] (Hiển thị ['c', 'd']) del numbers = [1, 2, 3, 4, 5] del numbers[0] print numbers (Hiển thị [2, 3, 4, 5]) [start:end]
  • 27. numbers = [1, 2, 3, 4, 5, 6, 7] del numbers[2:4] print numbers (Hiển thị [1, 2, 5, 6, 7]) + a = [1, 2] b = [1, 3] print a + b (Hiển thị [1, 2, 1, 3]) list.append(newvalue) newvalue list
  • 28. numbers = [1, 2, 3] numbers.append(4) print numbers (Hiển thị [1, 2, 3, 4] list.pop() numbers = [1, 2, 3] mynumber = numbers.pop() print mynumber (Hiển thị 3) print numbers (Hiển thị [1, 2])
  • 29. list.index(obj) aList = [123, 'xyz', 'zara', 'abc']; print "Index for xyz : ", aList.index('xyz') print "Index for zara : ", aList.index('zara') Index for xyz : 1 Index for zara : 2 list.reverse() list
  • 30. numbers = [1, 2, 3, 4] numbers.reverse() print numbers (Hiển thị [4, 3, 2, 1]) list.sort([func]) func list aList = [123, 'xyz', 'zara', 'abc', 'xyz'] aList.sort() print "List : ", aList (Hiển thị List : [123, 'abc', 'xyz', 'xyz', 'zara' ]) func() 0 -1 1
  • 31. (...) append() pop() mytuple = ('x', 'y', 'z') print mytuple (Hiển thị ('x', 'y', 'z')) {...}
  • 32. point = {'x': 1, 'y': 2} point = {'x': 3, 'y': 6, 'z' : 9} print point[x] (Hiển thị 3) dict[key] = value user = {'name': 'Jone', 'age': 30} user['country'] = 'Vietnam' print user (Hiển thị {'country': 'Vietnam', 'age': 30, 'name': 'Jone'}) dict.clear()
  • 36. import math math.__file__ (Ví dụ trả về '/usr/lib/python2.5/lib-dynload/math. so') import random random.__file__ (Ví dụ trả về '/usr/lib/python2.5/random.pyc') dir(modulename)
  • 37. dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degree s', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'fa ctorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma' , 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'lo g', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians ', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] dir() mymath.py
  • 38. def cong(a, b): return a + b def tru(a, b): return a - b def nhan(a, b): return a * b myexample.py mymath.py import mymath num1 = 1 num2 = 2 print 'Tong hai so la: ', mymath.cong(num1, num2)
  • 39. $ python myexample.py Tong hai so la: 3 .py __init__.py |-- mypack | |-- __init__.py | |-- mymodule1.py | |-- mymodule2.py | mymodule1
  • 40. import mypack.mymodule1 import mypack.mymodule1 as mymodule1 import mypack.mymodule1 as mod __init__.py __init__.py __init__.py import mypack.mysubpack.mysubsubpack.module
  • 41. class myclass([parentclass]): assignments def __init__(self): statements def method(): statements def method2(): statements class animal(): name = ''
  • 42. name = '' age = 0 def __init__(self, name = '', age = 0): self.name = name self.age = age def show(self): print 'My name is ', self.name def run(self): print 'Animal is running...' def go(self): print 'Animal is going...' class dog(animal): def run(self): print 'Dog is running...' myanimal = animal() myanimal.show() myanimal.run() myanimal.go() mydog = dog('Lucy') mydog.show() mydog.run() mydog.go()
  • 43. My Name is Animal is running... Animal is going... My Name is Lucy Dog is running... Animal is going... animal dog dog animal animal name age __init__(self) show() run() go() self
  • 45. fh = open(filepath, mode) filepath mode r w a
  • 46. r+ w+ a+ b rb wb ab rb+ wb+ ab+ f1 = open('test.txt', 'r') f2 = open('access_log', 'a+' open() closed mode name softspace
  • 47. print read([count]) f1 = open('test.txt', 'r') data = f1.read(); read() f2 = open('log.txt', 'r') buffdata = f2.read(1024) write()
  • 48. f2 = open('access_log', 'a+') f2.write('Attack detected') close() f1.close() f2.close() os.rename(old, new) import os os.rename('test.txt', 'test_new.txt') os.remove(file)
  • 50. os.listdir(dir) dir import os allfiles = os.listdir('/root/downloads') print allfiles os os os.chdir(path) os.getcwd() os.chmod(path, mode) os.chown(path, uid, gid) os.makedirs(path[, mode])
  • 53. from PIL import Image from PIL import Image im = Image.open("photo.jpg")
  • 54. im Image save(path, type) ... im.save('photo_new.jpg', 'JPEG') thumbnail from PIL import Image im = Image.open('photo.jpg') im.thumbnail((100, 100)) im.save('photo_thumbnail.jpg', 'JPEG') thumbnail
  • 55.
  • 57. import urllib2 import json response = urllib2.urlopen('https://api.github.com/ users/voduytuan/repos') data = json.load(response) print data
  • 58. import json mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}' data = json.loads(mystring) print data (Hiển thị: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd ': 4}) import json mydata = { 'name': 'John', 'age': 10 } jsonstring = json.dumps(mydata) print jsonstring (hiển thị: {"age": 10, "name": "John"})
  • 59. pip $ sudo pip install beautifulsoup4 lxml xml lxml
  • 60. pip sudo pip install lxml from bs4 import BeautifulSoup as Soup note = ''' <?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>Two of our famous Belgian Waff les with plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name>
  • 61. <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description>Light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> </breakfast_menu> ''' soup = Soup(note, 'xml') foods = soup.findAll('food') for x in foods: print x.find('name').string, ': ', x.price.stri ng Belgian Waffles : $5.95 Strawberry Belgian Waffles : $7.95 Soup
  • 63. MySQLdb pip $ sudo pip install MySQL-python
  • 64. import MySQLdb libmysqlclient.18.dylib libmysqlclient.18.dylib /usr/lib/ $ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18 .dylib /usr/lib/libmysqlclient.18.dylib
  • 65. import MySQLdb dbcon = MySQLdb.connect(host = 'localhost', user = 'myusername', passwd = 'mypassword', db = 'mydbname ') try
  • 66. import MySQLdb db = None try: db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'root', db = 'mysql') except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) if db: cur = db.cursor() cur.execute("SELECT VERSION()") ver = cur.fetchone() print "Database version : %s " % ver charset utf8 latin utf8
  • 67. ... db = MySQLdb.connect(host = 'localhost', user = 'ro ot', passwd = 'root', db = 'test', charset = 'utf8' ) cursor import MySQLdb db = MySQLdb.connect(host = 'localhost', user = 'ro ot', passwd = 'root', db = 'mysql'); cursor = db.cursor() sql = 'SELECT * FROM user' cursor.execute(sql) myusers = cursor.fetchall() myusers ((1, 'John'), (2, 'Doe')) cursor tuple
  • 68. Dictionary import MySQLdb db = MySQLdb.connect(host = 'localhost', user = 'ro ot', passwd = 'root', db = 'mysql') cursor = db.cursor(MySQLdb.cursors.DictCursor) ... cursor exectute(sql) fetchone() fetchall() fetchone() None fetchall()
  • 69. fetchmany(size) import MySQLdb db = MySQLdb.connect(...) db.close() cursor
  • 70. import MySQLdb db = MySQLdb.connect(...) cursor = db.cursor() cursor.close() db.close() ... cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s", ("John", "4")) ... %s execute()
  • 71. %s
  • 72. pip $ sudo pip install redis
  • 73. import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) import redis r = redis.StrictRedis(...) r.set('foo', 'bar') print r.get('foo') (Hiển thị 'bar') redis-py
  • 74. import redis r = redis.StrictRedis(...) r.set('foo', 'bar') pipe = r.pipeline() pipe.set('a', 1) pipe.set('b', 2) pipe.set('c', 3) pipe.get('foo') pipe.execute() execute() [True, True, True, 'bar']
  • 75. pylibmc pip $ sudo pip install pylibmc
  • 76. import pylibmc mc = pylibmc.Client(["127.0.0.1"], binary=True, beh aviors={"tcp_nodelay": True, "ketama": True}) import pylibmc mc = pylibmc.Client(...) mc.set('foo', 'bar') print mc.get('foo') (Hiển thị 'bar')
  • 77. pika pip $ sudo pip install pika
  • 78. import pika connection = pika.BlockingConnection(pika.Connectio nParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hel lo', body='Hello World!') print " [x] Sent 'Hello World!'" connection.close() hello Hello World! routing_key hello
  • 79. hello import pika connection = pika.BlockingConnection(pika.Connectio nParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') print ' [*] Waiting for messages. To exit press CTR L+C' def callback(ch, method, properties, body): print " [x] Received %r" % (body,) channel.basic_consume(callback, queue='hello', no_a ck=True) channel.start_consuming() connection
  • 81. requests pip $ sudo pip install requests
  • 82. import requests r = requests.get('https://api.github.com/events') r = requests.post("http://httpbin.org/post") r = requests.put("http://httpbin.org/put") r = requests.delete("http://httpbin.org/delete") r = requests.head("http://httpbin.org/get") r = requests.options("http://httpbin.org/get") GET params get()
  • 83. import requests payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get", params = payload) print(r.url) (Hiển thị: http://httpbin.org/get?key2=value2&key1= value1) data import requests payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", data = payload)
  • 84. files import requests url = 'http://httpbin.org/post' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files) Response status_code headers cookies text
  • 86. smtplib sender sender pip $ sudo pip install sender sender
  • 87. from sender import Mail, Message mail = Mail( "smtp.gmail.com", port = 465, username = "example@gmail.com", password = "yourpassword", use_tls = False, use_ssl = True, debug_level = False ) msg = Message("msg subject") msg.fromaddr = ("Vo Duy Tuan", "example@gmail.com") msg.to = "destuser@gmail.com" msg.body = "this is a msg plain text body" msg.html = "<b>this is a msg text body</b>" msg.reply_to = "example@gmail.com" msg.charset = "utf-8" msg.extra_headers = {} msg.mail_options = [] msg.rcpt_options = [] # Send message mail.send(msg)
  • 88. from sender import Mail, Message, Attachment mail = Main(...) msg = Message(..) ... # Open attached file and create Attachment object with open("photo01.jpg") as f: file01 = Attachment("photo01.jpg", "image/jpeg" , f.read()) msg.attach(file01) # Send message mail.send(msg) sender
  • 89.
  • 91. import socket s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for connecting') c.close() Got connection from Got connection from ('192.168.1.104', 60018) Thank you for connecting
  • 92. client.py import socket s = socket.socket() host = '127.0.0.1' port = 12345 s.connect((host, port)) print s.recv(1024) s.close socket.gethostname()