2014年10月31日

Python Study (2) - Concept

 
  • Study travel beginning
       Execute your first code Hollow World
        >>> print("Hollow World")
         Hollow World


    Python's core Data Type
           We understand  data type before studying any program. Python has built-in object types


    Data Type(Object type) Example
    Numbers int, float, long, complex
    Strings  
    Lists  
    Dictionaries  
    Tuples  
    Files  
    Sets set, frozenset
    Primitive types boolean,
    Program unit types Functions, modules, classes
    Implementation-related types compiled code, stack tracebacks


    1. Number
        Example: real number, float, double ...
    >>> 333 + 555
        888
    >>> 333 / 111
       3.0
    >>> 333 * 9
       2997
    >>> "happy " * 2 + " birthday"
       'happy happy  birthday'

    Module : math and random
    >>> import math
    >>> math.pi
    3.141592653589793
    >>> import random
    >>> random.random()
    0.7082048489415967
    >>> random.choice([2,4,6,8])
    4
    Note : intelligent complement => tab

     

    2. String
    (1) String is a array of char

    >>> S = 'Money'
    >>> S[0]
    'M'
    >>> S[-1]
    'y'
    >>> S[0:-1]
    'Mone'
    >>> len(S)
    5
    >>> S[:]
    'Money'
    >>> S[1:]
    'oney'
    >>> S[:3]
    'Mon'

    (2) Unicode String
    https://docs.python.org/2/howto/unicode.html.
    Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed.Python’s strings also come with full Unicode support  required for processing text in internationalized character sets.
     
    Python 2.X  
         In python 2.X, All Strings represent a collection of bytes, Python is default ASCII
         script. If you want change non-ASCII script for the script, you need put first line
         to declare encoding declaration.
       
         * Use Python Script edit the code and run . Ref: Use IDLE
          
         The length of the string is not 2 but rather 4, because each chinese word
         contain 2 bytes. len() function return length of bytes
       

    # coding=big5
    text = "哈囉"   #The word is a Chinese word than meas "hello"
    print len(text)

    4  # the result after run


        What does it happen when use encoding declaration. The result return 2 length
        of the string.

    # coding=big5   #encoding declaration
    text = u"哈囉"      #python 2.x use “u” to represent Unicode
    print len(text)

    2  # the result after run

     
         Note:  Python 2.x need to declarate encoding declaration.
         Both 3.X and 2.X use  “\x” hexadecimal  and  “\u” to represent Unicode

    >>> text = u’哈囉’
    >>> text
    u'\xab\xa2\xc5o'

     


    Python 3.x        
        Python 3.x all strings are unicode encode.

    text = "哈囉"   #The word is a Chinese word than meas "hello"
    print(len(text))

    4  # the result after run
              

    Encode and decode

    function description example
    unichr(int ) return unicode

    >>> unichr(80)
    u'P'

    chr(int ) return integer

    >>> chr(80)
    'P'

    ord(str ) return ASCII or Unicode

    >>> ord(u'A')
    65

    encode(str) return encode string >>>
    decode(str) return decode string  
    unicode return unicode string  

    (3) Pattern Matching
    Module : re


    >>>import re
              

    3. Lists
    Lists are ordered arbitrary collection of objects and they have no fixed size.they are sequence objetcs

    >>> L = ["toast", 10, "toast with egg", 12.5, "toast with ham", 15]
    >>> len(L)
    6

    >>> L[0:2]
    ['toast', 10]

    >>>L[:-1]
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham']

    >>>L + ["toast with vegetable", 20]
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15, 'toast with vegetable', 20]
              
    List functions
    function description example
    append add object at end of list >>> L.append(“toast with vegetable”)
    >>> L
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15, 'toast with vegetable']
    pop get object and remove >>> L.pop(-1)
    >>> L
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15]
    sort sort

    >>> M = ["Banana","Apple","Orange"]
    >>> M.sort()
    >>> M
    ['Apple', 'Banana', 'Orange']

    reverse  

    >>> M.reverse()
    >>> M
    ['Orange', 'Banana', 'Apple']

    keys return keys of the list  
    values return values of the list  

    List Arrary

    >>> L= [ [ 'toast','toast with egg','toast with ham','toast with vegetable'],
             [10,12.5,15,20]]
    >>> L[0]
    ['toast', 'toast with egg', 'toast with ham', 'toast with vegetable']

    >>> [row[1] for row in L]
    ['toast with egg', 12.5]
              
    range(int) : A built-in function is used to generate integers

    >>>List(range(5))
    [0,1,2,3,4]

    >>>for i in range(4):
                print(i)

    0
    1
    3
    4

    >>> list(range(1,4))
    [1,2,3]

    >>> list(range(1,8,2))
    [1, 3, 5, 7]
              
    map(function, iterable, ...) : map is a build-in function. Apply function to every item of iterable and return a list of the results.


    >>>List(range(5))

    >>> list1 = [1,2,3]
    >>> list2 = [1,2,3]
    >>> def sum(a,b):
        return a+b

    >>> list(map(sum, list1, list2))  #python 3.x use a list to store map 
    [2, 4, 6]
    >>>

              

    Dictionaries
    (1) kye/value
    (2) sequence


    >>> food = {"toast": 10, "toast with egg": 13.5, "toast with ham":15}
    >>> food["toast with egg"]
    13.5

    >>> food["toast with egg"]+=1
    >>> food["toast with egg"]
    14.5

    >>> food["toast with vegetable"] = 20
    >>> food["toast with vegetable"]
    20

              
    Dictionaries function

    dict : It is a name=value format and make dictionaries

    >>> newfood = dict(toast=15, toast_with_egg=20, toast_with_ham=25)}>>> newfood[toast_with_egg]
    Traceback (most recent call last):
      File "<pyshell#19>", line 1, in <module>
        newfood[toast_with_egg]
    NameError: name 'toast_with_egg' is not defined


    >>> newfood["toast_with_egg"]
    20

              

    zip :
    function :  zip([key1, key2, key3….], [value1, value2, value3…])

    >>>  dict(zip(['toast','toast with egg','toast with ham'],[10,12.5,15]))
    >>> newfood2["toast"]
    10

              
    build-in function

    >>> food= [ [ 'toast','toast with egg','toast with ham','toast with vegetable'],
             [10,12.5,15,20]]

            
    function description example
    keys show keys of the list

    >>> food.keys()
    ['toast', 'toast with ham', 'toast with vegetable', 'toast with egg']

    sort sort value of the list

    >>> foodMoney = list(food.values())
    >>> foodMoney.sort()
    >>> foodMoney
    [10, 14.5, 15, 20]

    values get values of the list

    >>> foodMoney = list(food.values())
    >>> foodMoney
    [10, 15, 20, 14.5]

    reverse  

    >>> foodMoney = list(food.values())
    >>> foodMoney.reverse()
    >>> foodMoney
    [20, 15, 14.5, 10]

       


    Tuples
    (1) sequence
    (2) fixed size
    (3) immutable (when the tuple is created, it connot be changed)

    >>> fruit = ("apple","organe","grape","banana")
    >>> fruit
    ('apple', 'organe', 'grape', 'banana')

    >>> fruit[0]
    'apple'

              
    built-in function

    >>> fruit = ("apple","organe","grape","banana")
    >>> fruit
    ('apple', 'organe', 'grape', 'banana')

    >>> fruit[0] = "tomato"
    Traceback (most recent call last):
      File "<pyshell#86>", line 1, in <module>
        fruit[0] = "tomato"
    TypeError: 'tuple' object does not support item assignment

              
    function description example
    index(object) return index of the tuple

    >>> fruit.index("banana")
    3

    count(object) return times of appear object in the tuple

    >>> fruit.count("apple")
    1









     

  • 2014年10月30日

    Python Study (1) - Introduce Python

     

    Why do I study Python  
        
         
    Each program has advantage itself, why I study python program? This book(*1)
          give us several  advantages :

          1   Software quality : Python script is designed to be readable , reusable and
               maintainable.
          2   Developer productivity : We don't need to complie program.
          3.  Program portability :  It is portable and  run on any operating  system
          4.  Module :  many module is written in python
          5.  Easy : Easy to learn, easy to read, easy to maintain

    User 
         Many companys adopt Python language to develop its products. such as :google,

          youtube, dropbox, google app engine...etc

    What do python do          
             1. GUI 

             2. OS program
             3. Internet program
             4. Component Integration
             5, Database program


    Python feature       
             1. Dynamic typing : you don't need to
    declare a type or variable size in advance.
                Such as:  i = 0 ;
             2. Automatic memory management :  it   when the object is created
    it can automatic create  and destroy

                  object. python
             3. third-party utilities : developers  contribute many packages that is write in
                 Python. To use these  save  your development time.
             4. easy to use : like human  syntax and simple read or write.
             5. free  :  It is free.

    Download python             
                  Download python install : https://www.python.org/downloads/

                   Python 2.X  : it is a legacy.
                   Python 3.X  : it is a evolution software and new features. such as: Unicode support.

                   which version should I use : ref https://wiki.python.org/moin/Python2orPython3
                 

           
        install

        Execute Python


     

  •  Python script execute          
               When the python code(.py) is executed first time, it will be into bytecode(.pyc).

                Bytecode is an implementation detail of the CPython interprete and low-level code.
                Bytecode makes execute faster than original source .
           
  • Python Virtual Machine(PVM)                  
             Python code is compiled to byte code(.pyc), PVM will execute the byte code.

              PVM is a engin of Python.



    • Setting variable environment
    1. Set your python environment variable
         
            Edit Path : C:\Python27\; C:\Python27\Scripts


        
         > python
     
        > ctrl + Z

      
        If you had installed many python versions, you can py -2 or  py -3 to switch   
         different  python version.

     
  •  Use IDLE
         1. Select IDLE , open Python Shell window    
     
          2. Execute python code
         


         3. To write python's script
        open New File.


        write a program

        Run Module or F5


        The script has executed and right to get answer
     
         

      
       
       
           
    Note:
           *1. Learning Python, 5th Edition, O'Reilly Media, ISBN:978-1-44935-573-9