Python 簡介

Python 語法基礎


In [115]:
#Value Assignment and Print Out Result
a = 3
print a +3


6

In [112]:
# Concat String and Integer Outputs Error
a = 1+"hello"
print a


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-112-f61e344c2257> in <module>()
      1 # Concat String and Integer Outputs Error
----> 2 a = 1+"hello"
      3 print a

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [113]:
#!/usr/bin/python
import sys

# This is a single line comment
def main():
    print 'Hello World'

if __name__ == '__main__':
    main()


Hello World

In [114]:
import sys
help(sys)
help(sys.exit)


Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://docs.python.org/library/sys

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.
    
    Dynamic objects:
    
    argv -- command line arguments; argv[0] is the script pathname if known
    path -- module search path; path[0] is the script directory, else ''
    modules -- dictionary of loaded modules
    
    displayhook -- called to show results in an interactive session
    excepthook -- called to handle any uncaught exception other than SystemExit
      To customize printing in an interactive session or to install a custom
      top-level exception handler, assign other functions to replace these.
    
    exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
      Assigning to sys.exitfunc is deprecated; use the atexit module instead.
    
    stdin -- standard input file object; used by raw_input() and input()
    stdout -- standard output file object; used by the print statement
    stderr -- standard error object; used for error messages
      By assigning other file objects (or objects that behave like files)
      to these, it is possible to redirect all of the interpreter's I/O.
    
    last_type -- type of last uncaught exception
    last_value -- value of last uncaught exception
    last_traceback -- traceback of last uncaught exception
      These three are only available in an interactive session after a
      traceback has been printed.
    
    exc_type -- type of exception currently being handled
    exc_value -- value of exception currently being handled
    exc_traceback -- traceback of exception currently being handled
      The function exc_info() should be used instead of these three,
      because it is thread-safe.
    
    Static objects:
    
    float_info -- a dict with information about the float inplementation.
    long_info -- a struct sequence with information about the long implementation.
    maxint -- the largest supported integer (the smallest is -maxint-1)
    maxsize -- the largest supported length of containers.
    maxunicode -- the largest supported character
    builtin_module_names -- tuple of module names built into this interpreter
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    hexversion -- version information encoded as a single integer
    copyright -- copyright notice pertaining to this interpreter
    platform -- platform identifier
    executable -- absolute path of the executable binary of the Python interpreter
    prefix -- prefix used to find the Python library
    exec_prefix -- prefix used to find the machine-specific Python library
    float_repr_style -- string indicating the style of repr() output for floats
    dllhandle -- [Windows only] integer handle of the Python DLL
    winver -- [Windows only] version number of the Python DLL
    __stdin__ -- the original stdin; don't touch!
    __stdout__ -- the original stdout; don't touch!
    __stderr__ -- the original stderr; don't touch!
    __displayhook__ -- the original displayhook; don't touch!
    __excepthook__ -- the original excepthook; don't touch!
    
    Functions:
    
    displayhook() -- print an object to the screen, and save it in __builtin__._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exc_clear() -- clear the exception state for the current thread
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setcheckinterval() -- control how often the interpreter checks for events
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

FUNCTIONS
    __displayhook__ = displayhook(...)
        displayhook(object) -> None
        
        Print an object to sys.stdout and also save it in __builtin__._
    
    __excepthook__ = excepthook(...)
        excepthook(exctype, value, traceback) -> None
        
        Handle an exception by displaying it with a traceback on sys.stderr.
    
    call_tracing(...)
        call_tracing(func, args) -> object
        
        Call func(*args), while tracing is enabled.  The tracing state is
        saved, and restored afterwards.  This is intended to be called from
        a debugger from a checkpoint, to recursively debug some other code.
    
    callstats(...)
        callstats() -> tuple of integers
        
        Return a tuple of function call statistics, if CALL_PROFILE was defined
        when Python was built.  Otherwise, return None.
        
        When enabled, this function returns detailed, implementation-specific
        details about the number of function calls executed. The return value is
        a 11-tuple where the entries in the tuple are counts of:
        0. all function calls
        1. calls to PyFunction_Type objects
        2. PyFunction calls that do not create an argument tuple
        3. PyFunction calls that do not create an argument tuple
           and bypass PyEval_EvalCodeEx()
        4. PyMethod calls
        5. PyMethod calls on bound methods
        6. PyType calls
        7. PyCFunction calls
        8. generator calls
        9. All other calls
        10. Number of stack pops performed by call_function()
    
    exc_clear(...)
        exc_clear() -> None
        
        Clear global information on the current exception.  Subsequent calls to
        exc_info() will return (None,None,None) until another exception is raised
        in the current thread or the execution stack returns to a frame where
        another exception is being handled.
    
    exc_info(...)
        exc_info() -> (type, value, traceback)
        
        Return information about the most recent exception caught by an except
        clause in the current stack frame or in an older stack frame.
    
    exit(...)
        exit([status])
        
        Exit the interpreter by raising SystemExit(status).
        If the status is omitted or None, it defaults to zero (i.e., success).
        If the status is numeric, it will be used as the system exit status.
        If it is another kind of object, it will be printed and the system
        exit status will be one (i.e., failure).
    
    getcheckinterval(...)
        getcheckinterval() -> current check interval; see setcheckinterval().
    
    getdefaultencoding(...)
        getdefaultencoding() -> string
        
        Return the current default string encoding used by the Unicode 
        implementation.
    
    getfilesystemencoding(...)
        getfilesystemencoding() -> string
        
        Return the encoding used to convert Unicode filenames in
        operating system filenames.
    
    getprofile(...)
        getprofile()
        
        Return the profiling function set with sys.setprofile.
        See the profiler chapter in the library manual.
    
    getrecursionlimit(...)
        getrecursionlimit()
        
        Return the current value of the recursion limit, the maximum depth
        of the Python interpreter stack.  This limit prevents infinite
        recursion from causing an overflow of the C stack and crashing Python.
    
    getrefcount(...)
        getrefcount(object) -> integer
        
        Return the reference count of object.  The count returned is generally
        one higher than you might expect, because it includes the (temporary)
        reference as an argument to getrefcount().
    
    getsizeof(...)
        getsizeof(object, default) -> int
        
        Return the size of object in bytes.
    
    gettrace(...)
        gettrace()
        
        Return the global debug tracing function set with sys.settrace.
        See the debugger chapter in the library manual.
    
    getwindowsversion(...)
        getwindowsversion()
        
        Return information about the running version of Windows as a named tuple.
        The members are named: major, minor, build, platform, service_pack,
        service_pack_major, service_pack_minor, suite_mask, and product_type. For
        backward compatibility, only the first 5 items are available by indexing.
        All elements are numbers, except service_pack which is a string. Platform
        may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,
        3 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain
        controller, 3 for a server.
    
    setcheckinterval(...)
        setcheckinterval(n)
        
        Tell the Python interpreter to check for asynchronous events every
        n instructions.  This also affects how often thread switches occur.
    
    setprofile(...)
        setprofile(function)
        
        Set the profiling function.  It will be called on each function call
        and return.  See the profiler chapter in the library manual.
    
    setrecursionlimit(...)
        setrecursionlimit(n)
        
        Set the maximum depth of the Python interpreter stack to n.  This
        limit prevents infinite recursion from causing an overflow of the C
        stack and crashing Python.  The highest possible limit is platform-
        dependent.
    
    settrace(...)
        settrace(function)
        
        Set the global debug tracing function.  It will be called on each
        function call.  See the debugger chapter in the library manual.

DATA
    __stderr__ = <open file '<stderr>', mode 'w'>
    __stdin__ = <open file '<stdin>', mode 'r'>
    __stdout__ = <open file '<stdout>', mode 'w'>
    api_version = 1013
    argv = ['-c', '-f', r'C:\Users\david\.ipython\profile_default\security...
    builtin_module_names = ('__builtin__', '__main__', '_ast', '_bisect', ...
    byteorder = 'little'
    copyright = 'Copyright (c) 2001-2012 Python Software Foundati...ematis...
    displayhook = <IPython.kernel.zmq.displayhook.ZMQShellDisplayHook obje...
    dllhandle = 503316480
    dont_write_bytecode = False
    exc_value = TypeError("<module 'sys' (built-in)> is a built-in module"...
    exec_prefix = r'C:\Python27'
    executable = r'C:\Python27\python.exe'
    flags = sys.flags(debug=0, py3k_warning=0, division_warn...unicode=0, ...
    float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...
    float_repr_style = 'short'
    hexversion = 34014192
    last_value = TypeError("unsupported operand type(s) for +: 'int' and '...
    long_info = sys.long_info(bits_per_digit=15, sizeof_digit=2)
    maxint = 2147483647
    maxsize = 2147483647
    maxunicode = 65535
    meta_path = []
    modules = {'ConfigParser': <module 'ConfigParser' from 'C:\Python27\Li...
    path = ['', r'C:\Python27\lib\site-packages\pip-1.1-py2.7.egg', r'C:\P...
    path_hooks = [<type 'zipimport.zipimporter'>]
    path_importer_cache = {'': None, r'C:\Python27': None, r'C:\Python27\D...
    platform = 'win32'
    prefix = r'C:\Python27'
    ps1 = 'In : '
    ps2 = '...: '
    ps3 = 'Out: '
    py3kwarning = False
    stderr = <IPython.kernel.zmq.iostream.OutStream object>
    stdin = <open file '<stdin>', mode 'r'>
    stdout = <IPython.kernel.zmq.iostream.OutStream object>
    subversion = ('CPython', '', '')
    version = '2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (...
    version_info = sys.version_info(major=2, minor=7, micro=3, releaseleve...
    warnoptions = []
    winver = '2.7'


Help on built-in function exit in module sys:

exit(...)
    exit([status])
    
    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is numeric, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

數值運算


In [105]:
#None: Evaluator
None==None, None==False, not(None)


Out[105]:
(True, False, True)

In [106]:
True, False==False, bool(42),not(42==True), \
(True or False) and not(False), True==1,not(1.000001 == 1), \
1.00000000000000000000000001 == 1


Out[106]:
(True, True, True, True, True, True, True, True)

In [109]:
#Integer: 
32, int('42'), 1/3, 1//3 , int(True), int(3.14)


Out[109]:
(32, 42, 0, 0, 1, 3)

In [108]:
#Long: 
1231980985476123891320918203981230123, long(1), 5L


Out[108]:
(1231980985476123891320918203981230123L, 1L, 5L)

In [110]:
#Float: 
4., 4.0, float(42), 1.0/3, complex(1j).real, complex(1j).imag,
4.2e3, 4.2E+3, 3**-1, float('nan'), float('inf')


Out[110]:
(4200.0, 4200.0, 0.3333333333333333, nan, inf)

In [111]:
#Complex: 
complex(3), complex(1j), complex('4+j'), complex(1,2), 1+1j


Out[111]:
((3+0j), 1j, (4+1j), (1+2j), (1+1j))

字串


In [7]:
#字串類別 (str) 是內建的
a = "hello world"
print a.__str__


<method-wrapper '__str__' of str object at 0x04A87D60>

In [1]:
#Double quote (“”) 跟 single quote (‘’)可以混用
a = 'this is a "book"'
print a


this is a "book"

In [11]:
# 使用 \ 作為換行符號
a = 'hi this is a l\
ong text'

print a

# 使用三個single quote 做多行處理
a = '''hi this is a l
ong text'''
print a


hi this is a long text
hi this is a l
ong text

In [15]:
# 字串操作
s = 'hello world'
print s[1]  #e
print s[-1] #d
print len(s)        ## 11
print s + ' yoyo'  ## hi there


e
d
11
hello world yoyo

In [20]:
# 使用str 做轉型
age = 30
print "my age is " + str(age)


my age is 30

In [24]:
# 帶有 format 的 String 
raw = '\n\t this is a \t line with format \t\n'
print raw   

# 使用 r 取得raw string
raw = r'\n\t this is a \t line with format \t\n'
print raw   

# 使用 repr 取得string 中的表示
raw = repr('\n\t this is a \t line with format \t\n')
print raw


	 this is a 	 line with format 	

\n\t this is a \t line with format \t\n
'\n\t this is a \t line with format \t\n'

In [25]:
# 字串函式
a = 'Qoo loves OOP'
a.split(), \
a.upper(), \
a.title(),


Out[25]:
(['Qoo', 'loves', 'OOP'], 'QOO LOVES OOP', 'Qoo Loves Oop')

In [26]:
import string
a = 'Qoo loves OOP'
string.join(a.split(), '-') # 'Qoo-loves-OOP'


Out[26]:
'Qoo-loves-OOP'

In [28]:
a = 'Qoo loves OOP'
'-'.join(a.split())


Out[28]:
'Qoo-loves-OOP'

In [44]:
s = 'hello'
s[1:4]   , \
s[1:]    , \
s[:]     , \
s[1:100] , \


Out[44]:
('ell', 'ello', 'hello', 'ello')

In [92]:
s = 'hello'
s[-1] , \
s[-4] , \
s[:-3] , \
s[-3:] , \


Out[92]:
('o', 'e', 'he', 'llo')

In [94]:
#String Formatting 
print 'The results are %.02f and %d' % (3.14159, 5)

#The results are 3.14 and 5


The results are 3.14 and 5

In [77]:
# -*- coding: utf-8 -*-
unistring = u'Handling 中文字串'
print type(unistring), len(unistring)
print unistring.encode('big5')
print unistring.encode('utf-8')
print unistring.encode('utf-8').decode('utf-8')
print unicode(unistring.encode('utf-8'), 'utf-8')


<type 'unicode'> 13
Handling ����r��
Handling 中文字串
Handling 中文字串
Handling 中文字串

List


In [78]:
a = [5, 6, 7, 8] # a = [5 6 7 8] 
print a[0] # 5
print a[2:4] # [7, 8] 
print a[-1] # 8 
print a[-2] # 7
print a[2:] # [7, 8]
print a[::2] # [5, 7]
print a[::-1] # [8, 7, 6, 5]
print len(a) # 4
print [min(a), max(a)] # [5, 8]


5
[7, 8]
8
7
[7, 8]
[5, 7]
[8, 7, 6, 5]
4
[5, 8]

In [82]:
a = [5, 6, 7, 8]
a.pop() # a = [5, 6, 7]
a.append(2) # a = [5, 6, 7, 2]
a.sort() # a = [2, 5, 6, 7]
a.reverse() # a = [7, 6, 5, 2]
a


Out[82]:
[7, 6, 5, 2]

In [83]:
a = [1, 2, 3]
b = a
a[1] = 2000
b


Out[83]:
[1, 2000, 3]

In [86]:
#List Copy
a = [1, 2, 3]

#List 
b = a[:]
print b

#List
b = list(a)
print b

#Extent
b = [] 
b.extend(a)
print b

#Iterration
b = []
for n in range(len(a)):
    b.append(a[n])
print b

#Foreach
b = [ e for e in a ]
b
print b


[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

In [91]:
# deep copy
a = [1, 2, 3]
import copy
aa = copy.deepcopy(a) # Deep Copy
a[1] = 2000
print aa


[1, 2, 3]

In [95]:
#List 可以裝載不同類型元素
print ['asap', 3]
print list("word"), 
print [['list'], ['of', 'lists']]
print list(('a', 1))

a = ['heterogeneous', 3]
a[1] + 5


['asap', 3]
['w', 'o', 'r', 'd'] [['list'], ['of', 'lists']]
['a', 1]
Out[95]:
8

In [100]:
nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ]   
print squares

## 篩選 values <= 2
nums = [2, 8, 1, 6]
small = [ n for n in nums if n <= 2 ]  ## [2, 1]
print small

## 篩選 包含 'a' 的 fruits, 並轉換為大寫
fruits = ['apple', 'cherry', 'bannana', 'lemon']
afruits = [ s.upper() for s in fruits if 'a' in s ]
print afruits


[1, 4, 9, 16]
[2, 1]
['APPLE', 'BANNANA']

字典 (Dictionary)


In [101]:
#Dictionary (Python hash): 
{}, { 'three': 3, 5: 'five'}, \
{'one': 'two', 'three': 'four'}, \
dict([['one', 'two' ], ['three', 'four']])


Out[101]:
({},
 {5: 'five', 'three': 3},
 {'one': 'two', 'three': 'four'},
 {'one': 'two', 'three': 'four'})

In [102]:
a = {'one': 'two', 'three': 'four'}
a.keys(), a.values()


Out[102]:
(['three', 'one'], ['four', 'two'])

In [103]:
d = {'Taiwan': 'Taipei', 'Japan': 'Tokyo'}

for (k,v) in d.items():
    print(k + ' has the capital ' + v)


Japan has the capital Tokyo
Taiwan has the capital Taipei

其他型態


In [15]:
#Tuple: 
(1, 2), ('a', 1), ('remember comma',), tuple(['a', 1])


Out[15]:
((1, 2), ('a', 1), ('remember comma',), ('a', 1))

In [33]:
#Set (distinct unordered): 
set(), set([1, 2]), set([2, 1]),\
set((2, 1)), set(range(0,5)) - set(range(4,10)),\
set([1, 2]) | set([3, 4])


Out[33]:
(set(), {1, 2}, {1, 2}, {1, 2}, {0, 1, 2, 3}, {1, 2, 3, 4})

In [34]:
#Frozenset (immutable): 
frozenset(), frozenset([1, 2]), \
frozenset([frozenset([1, 2]), frozenset([1, 2, 3])])


Out[34]:
(frozenset(),
 frozenset({1, 2}),
 frozenset({frozenset({1, 2}), frozenset({1, 2, 3})}))

迴圈與控制流程


In [3]:
#if - else
a = 9
for i in range(-1,9):
    print i
    if i == a:
        print(str(a) + ' found!')
        break
    else:
        print(str(a) + ' was not in the list')


-1
9 was not in the list
0
9 was not in the list
1
9 was not in the list
2
9 was not in the list
3
9 was not in the list
4
9 was not in the list
5
9 was not in the list
6
9 was not in the list
7
9 was not in the list
8
9 was not in the list

In [123]:
# from 1 to 10
for i in range(1,10):
    print i,
    
print

# step by 2
for i in range(1,10,2):
    print i,

print

# Iterate over list
a = [1,2,3,4,5]
for i in a:
    print i,


1 2 3 4 5 6 7 8 9
1 3 5 7 9 1 2 3 4 5

函式


In [5]:
def addNum(a, b):#Define Function
    return a+b #Return function 

print addNum(1,4)


5

In [45]:
#Function call with a variable number of input arguments
def myunion(x, *args):
    u = set(x)
    for y in args:
        u = u.union(set(y))
    return u

myunion([1]), myunion([1], [1, 2, 4], [3, 4])


Out[45]:
({1}, {1, 2, 3, 4})

In [46]:
#unknown named arguments
def my_key_union(x, **kwargs):
    union = set(x)
    for key, value in kwargs.items():
        if value:
            union.add(key)
    return union

#Example call:
my_key_union(['the'], stop=True, halt=False)


Out[46]:
{'stop', 'the'}

In [117]:
import math, sys # Importing modules.

def formatresult(res): # Define function. Remember ":"
    """This is the documentation for a function."""
    return "The result is %f" % res # Percentage for formating

if len(sys.argv) < 3: # Conditionals should be indended
    print("Too few input argument")
elif len(sys.argv) > 10: # Not 'elsif' or 'elseif'
    print("Too many input argument")
else:
    res = 0
    for n in range(1, len(sys.argv)): 
        try: res += float(sys.argv[n]) 
        except: pass # One-liner
    print(formatresult(res))

In [30]:
import math #Importing Modules
print math #Print Content

import sys #Importing Modules
print(sys.argv) #Print Argument

print range(1,len(sys.argv))


<module 'math' (built-in)>
['-c', '-f', 'C:\\Users\\david\\.ipython\\profile_default\\security\\kernel-06354f75-b837-4fb3-9c65-6a2184f8438f.json', "--IPKernelApp.parent_appname='ipython-notebook'", '--interrupt=976', '--parent=948']
[1, 2, 3, 4, 5]

物件導向程式設計

  • init() Constructor, 建構子
  • class 物件類型, e.g., <type 'list'>
  • doc 文件: 使用 help() 查詢
  • str() 印出物件
  • getitem() 取得內容
  • call() 當物件是函式時的呼叫方法

In [4]:
class Person():
    count = 0 # Static/class variable
    def __init__(self, name, city):
        self.name = name # Variable for the instance
        self.city = city # Variable for the instance
        Person.count += 1
    def number_of_persons(self):
        return Person.count

First = Person("David", "Chiayi")
First.number_of_persons() # 1

Second = Person("QOO", "coca-cola")
print Second.number_of_persons() # 2
First.name


2
Out[4]:
'David'

In [47]:
# OOP and Overloading
class MyInteger():
    def __init__(self, integer):
        print "constructor"
        self.integer = integer
    def __add__(self, integer): # Overloaded '+' operator
        if self.integer == 2 and integer == 2:
            return 5
        else:
            return self.integer + integer

a = MyInteger(3)
print a+5


constructor
8

In [56]:
#Derived Classes
class Vehicle():
    def my_own(self): return True
    
class Bicycle(Vehicle):
    def __init__(self, color): self.color = color
    def has_wheels(self): return True

class rent_bike(Bicycle):
    def my_own(self): return False
    
Ubike = rent_bike('yellow')
Ubike.my_own()


Out[56]:
False

檔案處理


In [57]:
#Writing Hello World Into Txt
fid = open('test.txt', 'w')
fid.write('Hello\nWorld')
fid.close()

In [58]:
#Load Hello World
fid = open('test.txt', 'r')
for line in fid: # Using file identifier as iterator
    print("Line: " + line.strip())
fid.close()


Line: Hello
Line: World

In [61]:
fid = open('test.txt', 'r')
s = fid.read() # Read the entire file
fid.close()
print "line",s


line Hello
World

In [126]:
#Line Counting
fid = open('test.txt')
k = 0
for line in fid:
    k = k + 1
print k
fid.close()


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-126-78be54fc5442> in <module>()
      1 #Line Counting
----> 2 fid = open('test.txt')
      3 k = 0
      4 for line in fid:
      5     k = k + 1

IOError: [Errno 2] No such file or directory: 'test.txt'

In [64]:
print len([ line for line in open('test.txt')])


2

例外處理


In [67]:
try:
    [ int(line) for line in open('test.txt') ] #You may remove int to see what happen
except IOError, message:
    print('An IO error', message)
except ValueError, message:
    print('A value error', message)
else:
    print('Succes')


Succes

In [75]:
def mydivide(a, b):
    try:
        return float(a)/b
    except ZeroDivisionError:
        return float('nan')
    except Exception, e:
        print 'Error:', e
        
#print(1./0)
mydivide(1,0)


Out[75]:
nan