Functions


In [17]:
def my_function():
    print "lin1"
    print "Hello From My Function!"

In [23]:
import os as os

In [39]:
x = os

In [40]:
x


Out[40]:
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>

In [10]:
my_function()


lin1
Hello From My Function!

In [11]:
def my_function_with_args(x, greeting):
    print "Hello, %s , From My Function!, I wish you %s"%(x, greeting)

In [24]:
my_function_with_args(,2)


Hello, <module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'> , From My Function!, I wish you 2

In [62]:
def sum_two_numbers(a, b):
    return a + b

In [63]:


In [47]:
[1,2,4]+[1,2,3,4]


Out[47]:
[1, 2, 4, 1, 2, 3, 4]

In [36]:
x


Out[36]:
3

In [6]:
# print a simple greeting 
my_function()

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!
x = sum_two_numbers(1,2)


Hello From My Function!
Hello, John Doe , From My Function!, I wish you a great year!

In [24]:
x


Out[24]:
3

In [71]:
def foo(first, second, third, *therest):
    print "First: %s" % first
    print "Second: %s" % second
    print "Third: %s" % third
    print "And all the rest... %s" % list(therest)

In [69]:
foo(1,2,3,[1,2,3,4,5])


First: 1
Second: 2
Third: 3
And all the rest... [1, 2, 3, 4, 5]

In [73]:
foo(1,2,3,4,5,6,7,8)


First: 1
Second: 2
Third: 3
And all the rest... [4, 5, 6, 7, 8]

In [74]:
def test(x , y):
    print x
    print y

In [80]:
test(2, y = 1)


2
1

In [84]:
def bar(x ,y, z, **options):
    return options

In [86]:
dic = bar(1,2,3,action="test")

In [97]:
def bar(first, second, third, **options):
    if options.get("action") == "sum":
        print "The sum is: %d" % (first + second + third)

    if options.get("action") == "first":
        return first

In [100]:
bar(1,2,3,action='first')


Out[100]:
1

In [23]:
result = bar(1, 2, 3, action = "sum", number = "first")
print "Result: %s" % result


The sum is: 6
Result: 1

In [2]:
result = bar(1, 2, 3, action = "sum")
print "Result: %s" % result


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-b5ea821e9289> in <module>()
----> 1 result = bar(1, 2, 3, action = "sum")
      2 print "Result: %s" % result

NameError: name 'bar' is not defined

In [101]:
#PYTHON在設定參數的時候,不用指定參數型態

def super_print(x):
    print x

super_print("cool")
super_print(13+5)
super_print([1,2,3,4,5])


cool
18
[1, 2, 3, 4, 5]

In [102]:
def super_print(x):
    for i in x:
        print i

super_print("cool")
#super_print(13+5)
super_print([1,2,3,4,5])


c
o
o
l
1
2
3
4
5

In [113]:
x = {'A':1, 'B':2}
for i in x:
    print x.get(i)


1
2

In [114]:
##練習:設計一個方法,可以加總一個列
x = [1,2,3,4,5]
sum_list(x)  ## 15


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-114-eda0b6b28ee4> in <module>()
      1 ##練習:設計一個方法,可以加總一個列
      2 x = [1,2,3,4,5]
----> 3 sum_list(x)  ## 15

NameError: name 'sum_list' is not defined

In [125]:
def sum_list(x):
    result = 0
    for i in x:
        result = result + i
    return result

In [136]:
def mutiple(l, x):
    result = []
    for i in l:
        result += [i*x]
        #result = result + [i * x]
    return result

In [135]:
mutiple([1,2,3,5],3)


Out[135]:
[3, 6, 9, 15]

In [130]:
sum_list([-2,3,4,5,6,61])


Out[130]:
77

In [132]:



Out[132]:
[[1, 2, 3], [1, 2, 3]]

In [32]:
##練習:設計一個方法,可以讓數字順序顛倒
x = [2,3,5,8,13]
reverse(x) # [13,8,5,3,2]


Out[32]:
[13, 8, 5, 3, 2]

In [146]:



Out[146]:
'AB'

In [103]:
##進階練習,設計一個方法計算Fibonacci數列的第n個值(1,1,2,3,5,8,13)

In [147]:
def reverse(x):
    result = []
    for i in range(len(x),0,-1):
        result.append(x[i-1])
    return result

In [152]:
def index(x):
    for i in range(len(x)):
        print i

In [156]:
index([2,3,4,6,7,8,'fsdf','fsa','fsa',2])


0
1
2
3
4
5
6
7
8
9

遞迴方法


In [168]:
def fibonacci(n):
    if n in (1,2):
        return 1
    if n > 2:
        return fibonacci(n-1) + fibonacci(n-2)

In [171]:
fibonacci(6)


6
5
4
3
3
4
3
Out[171]:
8

In [ ]:
##進階練習,使用for迴圈產生一fib數列

In [177]:
fib = [1,1]
for i in range(3,10):
    fib.append(fib[i-2]+fib[i-3])

In [175]:
fib


Out[175]:
[1, 1, 2, 3, 5, 8, 13, 21, 34]

In [178]:

Object


In [216]:
#Python 是物件導向語言
#每個東西都是物件,不同的物件之中有不同的方法來操作

class car: #物件名稱
    wheel = 4 #物件屬性
    
    #建立物件時自動呼叫的方法,參數預設要加入"self"
    def __init__(self, max_speed):
        self.max_speed = max_speed
        print "Let's Go!"
        
    def get_wheel(self):
        print "wheel = ", self.wheel
    
    def set_max_speed(self,speed):
        if speed > self.max_speed:
            print "Too Fast!"
        elif (speed <= self.max_speed) & (speed > 0):
            print "Safe!"
        else:
            print "Stop"

In [221]:
#我們不能直接操作物件,要操作物件之前,必須將物件實體化
carA = car(90)


Let's Go!

In [223]:
carA.max_speed


Out[223]:
90

In [232]:
carA.set_max_speed(100)


Too Fast!

In [233]:
carA.speed


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-233-4c3ccbd36d3d> in <module>()
----> 1 carA.speed

AttributeError: car instance has no attribute 'speed'

In [202]:
car.get_wheel()
car.set_max_speed(0)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-202-7fccb28d79c1> in <module>()
----> 1 car.get_wheel()
      2 car.set_max_speed(0)

TypeError: unbound method get_wheel() must be called with car instance as first argument (got nothing instead)

In [ ]:
##修改程式碼,讓下面操作可以執行
car.get_speed()

In [227]:
carB=car(100)
carC=car(70)


Let's Go!
Let's Go!

In [231]:
carB.max_speed


Out[231]:
100

import Modules


In [ ]:


In [234]:
import urllib

In [235]:
help(urllib.urlopen)


Help on function urlopen in module urllib:

urlopen(url, data=None, proxies=None)
    Create a file-like object for the specified URL to read from.


In [12]:
urllib.urlopen("http://www.pchome.com.tw")


Out[12]:
<addinfourl at 4519164384 whose fp = <socket._fileobject object at 0x10d5b1f50>>

In [236]:
import urllib
dir(urllib)
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_ftperrors', '_get_proxies', '_get_proxy_settings', '_have_ssl', '_hexdig', '_hextochr', '_hostprog', '_is_unicode', '_localhost', '_noheaders', '_nportprog', '_passwdprog', '_portprog', '_queryprog', '_safe_map', '_safe_quoters', '_tagprog', '_thishost', '_typeprog', '_urlopener', '_userprog', '_valueprog', 'addbase', 'addclosehook', 'addinfo', 'addinfourl', 'always_safe', 'basejoin', 'c', 'ftpcache', 'ftperrors', 'ftpwrapper', 'getproxies', 'getproxies_environment', 'getproxies_macosx_sysconf', 'i', 'localhost', 'main', 'noheaders', 'os', 'pathname2url', 'proxy_bypass', 'proxy_bypass_environment', 'proxy_bypass_macosx_sysconf', 'quote', 'quote_plus', 'reporthook', 'socket', 'splitattr', 'splithost', 'splitnport', 'splitpasswd', 'splitport', 'splitquery', 'splittag', 'splittype', 'splituser', 'splitvalue', 'ssl', 'string', 'sys', 'test', 'test1', 'thishost', 'time', 'toBytes', 'unquote', 'unquote_plus', 'unwrap', 'url2pathname', 'urlcleanup', 'urlencode', 'urlopen', 'urlretrieve']


Out[236]:
['ContentTooShortError',
 'FancyURLopener',
 'MAXFTPCACHE',
 'URLopener',
 '__all__',
 '__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '__version__',
 '_ftperrors',
 '_get_proxies',
 '_get_proxy_settings',
 '_have_ssl',
 '_hexdig',
 '_hextochr',
 '_hostprog',
 '_is_unicode',
 '_localhost',
 '_noheaders',
 '_nportprog',
 '_passwdprog',
 '_portprog',
 '_queryprog',
 '_safe_map',
 '_safe_quoters',
 '_tagprog',
 '_thishost',
 '_typeprog',
 '_urlopener',
 '_userprog',
 '_valueprog',
 'addbase',
 'addclosehook',
 'addinfo',
 'addinfourl',
 'always_safe',
 'basejoin',
 'c',
 'ftpcache',
 'ftperrors',
 'ftpwrapper',
 'getproxies',
 'getproxies_environment',
 'getproxies_macosx_sysconf',
 'i',
 'localhost',
 'main',
 'noheaders',
 'os',
 'pathname2url',
 'proxy_bypass',
 'proxy_bypass_environment',
 'proxy_bypass_macosx_sysconf',
 'quote',
 'quote_plus',
 'reporthook',
 'socket',
 'splitattr',
 'splithost',
 'splitnport',
 'splitpasswd',
 'splitport',
 'splitquery',
 'splittag',
 'splittype',
 'splituser',
 'splitvalue',
 'ssl',
 'string',
 'sys',
 'test',
 'test1',
 'thishost',
 'time',
 'toBytes',
 'unquote',
 'unquote_plus',
 'unwrap',
 'url2pathname',
 'urlcleanup',
 'urlencode',
 'urlopen',
 'urlretrieve']

In [16]:
from urllib import urlopen

In [1]:
urlopen("http://www.pchome.com.tw")


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-d012b0fe6ac9> in <module>()
----> 1 urlopen("http://www.pchome.com.tw")

NameError: name 'urlopen' is not defined

Stat Object


In [27]:
class stat:
    
    def is_list(self, input_list):
        if isinstance(input_list, list):
            pass
        else:
            raise ValueError("Must pass a list.")
    
    def sum_list(self, input_list):
        self.is_list(input_list)
        result = 0
        for l in input_list:
            result += l
        return result
    
    def mean_list(self, input_list):
        self.is_list(input_list)
        total = self.sum_list(input_list)
        n = len(input_list)
        return float(total)/n
    
    def var_list(self, input_list):
        self.is_list(input_list)
        X = self.mean_list(input_list)
        result = 0
        for l in input_list:
            result += (l-X)**2
        return result
    
    def std_list(self)

In [28]:
s = stat()

In [29]:
s.sum_list([1,2,3,4,5])


Out[29]:
15

In [30]:
s.mean_list([1,1,98])


Out[30]:
33.333333333333336

In [34]:
s.var_list([1,2,3,4,5,6])


Out[34]:
17.5