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]:
In [10]:
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)
In [62]:
def sum_two_numbers(a, b):
return a + b
In [63]:
In [47]:
[1,2,4]+[1,2,3,4]
Out[47]:
In [36]:
x
Out[36]:
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)
In [24]:
x
Out[24]:
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])
In [73]:
foo(1,2,3,4,5,6,7,8)
In [74]:
def test(x , y):
print x
print y
In [80]:
test(2, y = 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]:
In [23]:
result = bar(1, 2, 3, action = "sum", number = "first")
print "Result: %s" % result
In [2]:
result = bar(1, 2, 3, action = "sum")
print "Result: %s" % result
In [101]:
#PYTHON在設定參數的時候,不用指定參數型態
def super_print(x):
print x
super_print("cool")
super_print(13+5)
super_print([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])
In [113]:
x = {'A':1, 'B':2}
for i in x:
print x.get(i)
In [114]:
##練習:設計一個方法,可以加總一個列
x = [1,2,3,4,5]
sum_list(x) ## 15
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]:
In [130]:
sum_list([-2,3,4,5,6,61])
Out[130]:
In [132]:
Out[132]:
In [32]:
##練習:設計一個方法,可以讓數字順序顛倒
x = [2,3,5,8,13]
reverse(x) # [13,8,5,3,2]
Out[32]:
In [146]:
Out[146]:
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])
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)
Out[171]:
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]:
In [178]:
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)
In [223]:
carA.max_speed
Out[223]:
In [232]:
carA.set_max_speed(100)
In [233]:
carA.speed
In [202]:
car.get_wheel()
car.set_max_speed(0)
In [ ]:
##修改程式碼,讓下面操作可以執行
car.get_speed()
In [227]:
carB=car(100)
carC=car(70)
In [231]:
carB.max_speed
Out[231]:
In [ ]:
In [234]:
import urllib
In [235]:
help(urllib.urlopen)
In [12]:
urllib.urlopen("http://www.pchome.com.tw")
Out[12]:
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]:
In [16]:
from urllib import urlopen
In [1]:
urlopen("http://www.pchome.com.tw")
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]:
In [30]:
s.mean_list([1,1,98])
Out[30]:
In [34]:
s.var_list([1,2,3,4,5,6])
Out[34]: