KEMBAR78
Python101 | PDF
Python 101
 Kiattisak Anoochitarom
     NSC Camp #5
Who’s Invent ?



    Guido van Rossum
    Software Engineer at Google inc.
Programming Structure

 ‣ Indentation
 ‣ strong & dynamic type
 ‣ short and readable code
 ‣ interpreter style
PEP-8

เขียน Python โดยไม่อ่าน PEP-8 ถือว่าเป็น “บาป”
 - อ่านง่าย (Readability)
 - กลมกลืน (Consistency)

Guido บอกว่า Programmer ส่วนใหญ่มักจะอ่าน Code มากกว่า
เขียน ดังนั้นถ้าจะเขียนควรเขียนให้อ่านง่าย
PEP-8 Overview [1]

‣ 4 white spaces or 1 tab for indentation
‣ อย่าให้แต่ละบรรทัดเกิน 79 ตัวอักษร
‣ คั่นส่วนต่างๆ ของโปรแกรมด้วยการเว้นบรรทัด
PEP-8 Overview [2]
import library 1 ตัวต่อ 1 บรรทัด
import ที่ด้านบนของไฟล์เสมอ
import cv
import bs4                                          Yes:
from subprocess import Popen, PIPE                    x=1
                                                      y=2
                  Yes: spam(ham[1], {eggs: 2})        long_variable = 3
                  No: spam( ham[ 1 ], { eggs: 2})   No:
                                                      x            =1
                  Yes: dict[‘key’] = list[index]      y             =2
                  No: dict [‘key’] = list [index]     long_variable = 3

    อย่าใช้ whitespace พร่ําเพรื่อ (1 บรรทัดไม่ควรเกิน 79 ตัวอักษร)
Data Type

    String                 str = ‘message’
   Integer                   number = 20
Floating Point                pi = 3.14159
   Boolean              isParse = True, False
    None                          None
     List                    list = [1, 2, 3]
  Dictionary        me = {“name”: “Bas”, “No”: 1}
Class instance              a = MyClass()
Operator
Basic Operator
 +, -, *, /, %, **, &, |       warning!
                               - int/int == int
                               - int**(-int) == float
Comparison Operator
                               - int/float == float
>, >=, <, <=, ==, !=, is       - string + string == concat string
                               - string * int == multiple string
                               - list + list = list



shortly
i = i + 1 == i += 1
Logical Operator
ใน Python เราจะใช้ & และ | (Pipe) เพื่อทํา and, or Operation
แต่ใน Python ก็มี Operator พิเศษและนิยมใช้กันนั่นคือ


                        and , or

                                       shortly logical operation
                                              x &= (a == b)
                                                   ==
                                           x = x and (a == b)
Control Statement (if)
                                       If
                          condition statement
         เงื่อนไขของ if ไม่ต้องใส่วงเล็บ เว้นแต่ว่าเงื่อนไขจะมีหลายบรรทัด



number = int(input(“Enter Number: “))       number = int(input(“Enter Number: “))
if number > 0:                              if number % 2 == 0 or number % 4 == 0
   print “Number is Positive”                  or number % 5 == 0:
elif number < 0:                                  print ‘Number divided by 2, 4, 5’
   print “Number is Negative”
else:
   print “Number is Zero”
Control Statement (for)
  For (foreach)
    loop statement
                          list = [7, 8, 9, 10]
for x in xrange(10):      for index, value in enumerate(list):
  print x                      print index, value

for x in xrange(3, 20):
  print x
                           x=0                Endless Loop
name = [‘a’, ‘b’, ‘c’]     while (x <= 10):   while True:
for x in name               print x             if condition:
  print x                   x += 1                 break;
Play with List, Dictionary



       string method and slice
     list and list method demo
           dictionary demo
     mixed type list, dictionary
Function
Function Syntax:
   def function_name(set of parameter):
     statement ..
     statement ..

def fibonacci(n):
  fibo = 0;
  for k in xrange(0, int(math.floor((n - 1) / 2)) + 1):
     fibo += math.factorial(n - k - 1) / 
          (math.factorial(k) * math.factorial(n - k - 1 - k))
  return fibo


Muti-Return Data
Python OOP
- Class = แม่พิมพ์ขนม
- Object, Instance = ขนม
- Python Class ก็เช่นเดียวกัน
- Python Class จะ subclass จาก Class object เสมอ


                 Demo:
                 - create class
                 - constructor and destructor
                 - create class instance
                 - using class
Read and Write File
open(‘filename’, ‘mode’)
             r = read # เปิดไฟล์เพื่ออ่าน
             w = write # เปิดไฟล์เพื่อเขียนทับ
             a = append # เปิดไฟล์เพื่อเขียนต่อ

file = open(‘filename.txt’, r)
file.read() # อ่านไฟล์ทั้งหมดเป็น String
file.readline() # อ่านไฟล์ทีละบรรทัด
file.readlines() # อ่านไฟล์ทุกบรรทัดออกมาเป็น List of String

file.write(‘string’) # เขียน String ทั้งหมดลงไฟล์
file.writelines([list of string]) # เขียน List of String ลงไฟล์
1-liner
บรรทัดเดียวก็เสียวได้




                   - sum
                   - list comprehensive
                   - shorten if
Tools

Editor
 - Vim
 - Sublime              Interactive Shell
                         - python shell
                         - ipython
IDE                      - bpython
 - Eclipse + PyDev       - IDLE
 - Eric IDE
 - Komodo
Libraries



Libraries ของ Python มีเยอะมาก
หาได้จาก PyPI - http://pypi.python.org/pypi
It’s Application

Digital Image Processing (Python Imaging Library)
           Computer Vision (OpenCV)
            Web Framework (Django)
          Web Server (Gunicorn, Tornado)
  Web Client (Beautiful Soup, urllib3, html5lib)
       Content Management System (Plone)
       Natural Language Processing (NLTK)

Python101

  • 1.
    Python 101 KiattisakAnoochitarom NSC Camp #5
  • 2.
    Who’s Invent ? Guido van Rossum Software Engineer at Google inc.
  • 3.
    Programming Structure ‣Indentation ‣ strong & dynamic type ‣ short and readable code ‣ interpreter style
  • 4.
    PEP-8 เขียน Python โดยไม่อ่านPEP-8 ถือว่าเป็น “บาป” - อ่านง่าย (Readability) - กลมกลืน (Consistency) Guido บอกว่า Programmer ส่วนใหญ่มักจะอ่าน Code มากกว่า เขียน ดังนั้นถ้าจะเขียนควรเขียนให้อ่านง่าย
  • 5.
    PEP-8 Overview [1] ‣4 white spaces or 1 tab for indentation ‣ อย่าให้แต่ละบรรทัดเกิน 79 ตัวอักษร ‣ คั่นส่วนต่างๆ ของโปรแกรมด้วยการเว้นบรรทัด
  • 6.
    PEP-8 Overview [2] importlibrary 1 ตัวต่อ 1 บรรทัด import ที่ด้านบนของไฟล์เสมอ import cv import bs4 Yes: from subprocess import Popen, PIPE x=1 y=2 Yes: spam(ham[1], {eggs: 2}) long_variable = 3 No: spam( ham[ 1 ], { eggs: 2}) No: x =1 Yes: dict[‘key’] = list[index] y =2 No: dict [‘key’] = list [index] long_variable = 3 อย่าใช้ whitespace พร่ําเพรื่อ (1 บรรทัดไม่ควรเกิน 79 ตัวอักษร)
  • 7.
    Data Type String str = ‘message’ Integer number = 20 Floating Point pi = 3.14159 Boolean isParse = True, False None None List list = [1, 2, 3] Dictionary me = {“name”: “Bas”, “No”: 1} Class instance a = MyClass()
  • 8.
    Operator Basic Operator +,-, *, /, %, **, &, | warning! - int/int == int - int**(-int) == float Comparison Operator - int/float == float >, >=, <, <=, ==, !=, is - string + string == concat string - string * int == multiple string - list + list = list shortly i = i + 1 == i += 1
  • 9.
    Logical Operator ใน Pythonเราจะใช้ & และ | (Pipe) เพื่อทํา and, or Operation แต่ใน Python ก็มี Operator พิเศษและนิยมใช้กันนั่นคือ and , or shortly logical operation x &= (a == b) == x = x and (a == b)
  • 10.
    Control Statement (if) If condition statement เงื่อนไขของ if ไม่ต้องใส่วงเล็บ เว้นแต่ว่าเงื่อนไขจะมีหลายบรรทัด number = int(input(“Enter Number: “)) number = int(input(“Enter Number: “)) if number > 0: if number % 2 == 0 or number % 4 == 0 print “Number is Positive” or number % 5 == 0: elif number < 0: print ‘Number divided by 2, 4, 5’ print “Number is Negative” else: print “Number is Zero”
  • 11.
    Control Statement (for) For (foreach) loop statement list = [7, 8, 9, 10] for x in xrange(10): for index, value in enumerate(list): print x print index, value for x in xrange(3, 20): print x x=0 Endless Loop name = [‘a’, ‘b’, ‘c’] while (x <= 10): while True: for x in name print x if condition: print x x += 1 break;
  • 12.
    Play with List,Dictionary string method and slice list and list method demo dictionary demo mixed type list, dictionary
  • 13.
    Function Function Syntax: def function_name(set of parameter): statement .. statement .. def fibonacci(n): fibo = 0; for k in xrange(0, int(math.floor((n - 1) / 2)) + 1): fibo += math.factorial(n - k - 1) / (math.factorial(k) * math.factorial(n - k - 1 - k)) return fibo Muti-Return Data
  • 14.
    Python OOP - Class= แม่พิมพ์ขนม - Object, Instance = ขนม - Python Class ก็เช่นเดียวกัน - Python Class จะ subclass จาก Class object เสมอ Demo: - create class - constructor and destructor - create class instance - using class
  • 15.
    Read and WriteFile open(‘filename’, ‘mode’) r = read # เปิดไฟล์เพื่ออ่าน w = write # เปิดไฟล์เพื่อเขียนทับ a = append # เปิดไฟล์เพื่อเขียนต่อ file = open(‘filename.txt’, r) file.read() # อ่านไฟล์ทั้งหมดเป็น String file.readline() # อ่านไฟล์ทีละบรรทัด file.readlines() # อ่านไฟล์ทุกบรรทัดออกมาเป็น List of String file.write(‘string’) # เขียน String ทั้งหมดลงไฟล์ file.writelines([list of string]) # เขียน List of String ลงไฟล์
  • 16.
  • 17.
    Tools Editor - Vim - Sublime Interactive Shell - python shell - ipython IDE - bpython - Eclipse + PyDev - IDLE - Eric IDE - Komodo
  • 18.
    Libraries Libraries ของ Pythonมีเยอะมาก หาได้จาก PyPI - http://pypi.python.org/pypi
  • 19.
    It’s Application Digital ImageProcessing (Python Imaging Library) Computer Vision (OpenCV) Web Framework (Django) Web Server (Gunicorn, Tornado) Web Client (Beautiful Soup, urllib3, html5lib) Content Management System (Plone) Natural Language Processing (NLTK)